簡體   English   中英

使用嵌套的 Map 打印 Map

[英]Printing a Map with a nested Map

我有以下類型的 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.

如何正確打印 Map 使其看起來像這樣:

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

提前感謝您的任何想法!

Map具有簡單的迭代器forEach((key, value) -> your_consumer) ,嵌套 map 中的條目可以轉換為使用Collectors.joining連接的字符串,因此可以按如下方式打印:

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

如果我對您的理解正確:在外部循環中,您應該迭代嵌套映射(作為值),而在內部循環中,您最終可以迭代嵌套 map 的鍵和值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM