首页 > 解决方案 > 如何以 Java 格式打印嵌套的 Hashmap

问题描述

我遇到了在 Java 中打印格式化到控制台的嵌套 Hashmap 的问题。我的地图结构是这样的:private static Map<String, Map<YearInterval, List<String>>> comicFilmMap = new HashMap<>();

输出应如下所示:ComicName: Year FilmTitle FilmTitle

我尝试了一个 foreach 但无法让它工作。

标签: javadictionaryhashmap

解决方案


最简单的方法是,您可以使用 Map.Entry 接口遍历您的哈希图。以下是相同的伪代码:

foreach(Entry entry: comicFileMap.entryset()){
  sysout(entry.getKey()); // this will be your comicName

  foreach(Entry entryChild: entry.getValue()){ //the getValue() will be again 
                                               //hashmap()
     sysout(entrychild.getkey());
     foreach(String str: entryChild.getValue()){//this loop will print list of 
                                                //string
       sysout(str); 
     }
  }
}

有关更多信息,您可以使用https://www.geeksforgeeks.org/map-entry-interface-java-example/链接


推荐阅读