使用嵌套地图打印地图

Printing a Map with a nested Map

我有以下类型的地图: HashMap<String, Map<String, Integer>> resultMap = new HashMap<>();

哪里String(Key) = Website address;

Map<String,Integer> = String(key) -search word, Integer(value) - counter for found words.

如何正确打印地图,使其看起来像这样:

  1. webSite1 - randomWord = 30,randomWord2 = 15,randomWord3 = 0
  2. webSite2 - randomWord = 9,randomWord2 = 8,randomWord3 = 1

提前感谢您的任何想法!

Map 有简单的迭代器 forEach((key, value) -> your_consumer),嵌套映射中的条目可以转换为使用 Collectors.joining 连接的字符串,因此可以按如下方式打印:

resultMap.forEach((k, v) ->
    System.out.println(k + " - " + 
        v.entrySet().stream()
         .map(e -> e.getKey() + "=" + e.getValue())
         .collect(Collectors.joining(", "))
);

如果我没听错: 在外循环中,您应该迭代嵌套映射(作为值), 在内部循环中,您最终可以迭代嵌套映射的键和值。

HashMap<String, Map<String, Integer>> map = new HashMap<>();
        for (Map<String, Integer> nestedMap : map.values()) 
        {
            for (String key : nestedMap.keySet()) {
                // some actions here
            }
            
            for (Integer value : nestedMap.values()) {
                // some actions here
            }
        }