Steve0320
Steve0320

Reputation: 23

Printing all data from HashMap

The code looks like this.

    public class Album {
    public String currentTitle;
    public HashMap<String, List<Music>> albumList = new HashMap<String, List<Music>>();

    //setting the album's title
    public Album(String albumTitle) {
        this.currentTitle = albumTitle; //represents object's name
        albumList.put(currentTitle, null);
    }

    //add music to album
    public void addMusicToThis(Music music) {
        //only if value is empty
        if(albumList.get(currentTitle) == null) {
            albumList.put(currentTitle, new ArrayList<Music>());
        }
        albumList.get(currentTitle).add(music);
    }

    public void printMusicList() {

    }
}

and I want to print all values for the specific album, like

Album album = new Album("Test1");
Album album2 = new Album("Test2");
album.addMusicToThis(something);  //this code works fine
album2.addMusicToThis(something2);

album.printMusicList();   //maybe "something"
album2.printMusicList();  //maybe "something2"

but the hashMap's values are all set to List, and I can't find the way to print the musics out. And assume that music's name is all set.

Upvotes: 0

Views: 136

Answers (4)

user3756610
user3756610

Reputation: 13

I think you should add the albumTitle as an argument of the printMusicList function.

For example

  public void printMusicList(String albumTitle) {
      List<Music> musics = albumList.get(albumTitle);
      for (Music music : musics) {
          System.out.println(music);
      }
  }

or if you want to print it all

  public void printMusicList() {
      Set<String> keys = albumList.keySet();
      for (String key : keys) {
          List<Music> musics = albumList.get(key);
          for (Music music : musics) {
              System.out.println(music);
          }
      }
  }

Upvotes: 0

Antho Christen
Antho Christen

Reputation: 1329

You must iterate over the obtained list and print the individual entries

In Java 8 you can,

albumList.get(currentTitle).forEach((music) -> System.out.println(musice.getRequiredDetails)})

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191728

You just get the list for a particular string, and iterate it

for(Music m : albumList.get(this.currentTitle)) {
    System.out.println(m.getName());
}

It's not really clear why you're using a Hashmap, though. Your key can never change.

Upvotes: 1

cecunami
cecunami

Reputation: 1037

You can call albumList.entrySet() which is actually iterable, traverse it and print it however you like

Upvotes: 0

Related Questions