【问题标题】:Printing a Map with a nested Map使用嵌套地图打印地图
【发布时间】:2021-04-18 07:30:57
【问题描述】:

我有以下类型的地图: 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

提前感谢您的任何想法!

【问题讨论】:

  • 到目前为止你尝试过什么?是什么导致了您的问题?
  • 我不明白如何通过 foreach 从生成的 Map 中检索数据

标签: java arrays collections printing hashmap


【解决方案1】:

Map有简单的迭代器forEach((key, value) -&gt; your_consumer),嵌套映射中的条目可以转换成使用Collectors.joining连接的字符串,所以打印可以如下:

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

【讨论】:

    【解决方案2】:

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

    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
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 1970-01-01
      • 2015-10-05
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多