[英]Iterating over List in a Map
迭代“非規范化”集合映射的最佳方法是什么?
例如,我有以下地圖:
Map<String, List<String>> relations;
為了迭代每個鍵 - >每個值我做的事情如下:
for (Entry<String,List<String>> e : relations.entries()) {
for (String s : e.getValue()) {
System.out.println(e.getKey() + " - " + s);
}
}
是否有一種優雅的方式來解決它與一些裝飾器左右?
我希望找到類似的東西:
for(Entry e : Collections.getDenormalizeEntriesFromMapOfCollection(myMap)) {
System.out.println(e.getKey() + " - " + e.getValue());
}
這樣會產生相同的結果,只是在第二種情況下,每個鍵都有一個條目 - >集合項。
我建議你看一下guavas MultiMap
實現。 它已經有了這種迭代器:
要將Map<K, Collection<V>
轉換為MultiMap<K, V>
您可以使用實用程序方法:
public static <K,V> Multimap<K,V> toMultiMap(Map<K,? extends Collection<V>> m) {
LinkedListMultimap<K, V> multimap = LinkedListMultimap.create();
for (Entry<K, ? extends Collection<V>> e : m.entrySet())
multimap.putAll(e.getKey(), e.getValue());
return multimap;
}
用法:
public static void main(String[] args) {
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Hello", Arrays.asList(1, 2));
map.put("World!", Arrays.asList(3));
Multimap<String, Integer> multimap = toMultiMap(map);
Iterator<Entry<String, Integer>> it = multimap.entries().iterator();
while (it.hasNext())
System.out.println(it.next());
}
輸出:
Hello=1
Hello=2
World=3
沒有比你用來迭代Map<String, List<String>>
更優雅的方式了。 但更優雅的做法是使用Guava ListMultimap ,它提供了一個entries()
方法,您可以在其上直接迭代,而不需要嵌套循環。
我認為Eclipse的調試器正是如此,你可以查看實現。 否則,您可以在實用程序類中編寫輔助方法,例如,因為據我所知,Collections框架不支持此方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.