[英]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 使其看起來像這樣:
提前感謝您的任何想法!
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.