代码看起来像这样。

    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() {

    }
}


我想打印特定专辑的所有值,例如

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"


但是hashMap的值都设置为List,我找不到打印音乐的方法。
并假设已设置好音乐的名称。

最佳答案

您必须遍历所获得的列表并打印各个条目

在Java 8中,您可以

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

09-25 17:18