简体   繁体   English

迭代Map中的List

[英]Iterating over List in a Map

What is the best way to iterate over a "de-normalized" map of collections? 迭代“非规范化”集合映射的最佳方法是什么?

For example, I have the following map: 例如,我有以下地图:

Map<String, List<String>> relations;

In order to iterate over each key -> each value I do something like: 为了迭代每个键 - >每个值我做的事情如下:

for (Entry<String,List<String>> e : relations.entries()) {
   for (String s : e.getValue()) {
       System.out.println(e.getKey() + " - " + s);
   }
}

Is there an elegant way to solve it with some decorator or so? 是否有一种优雅的方式来解决它与一些装饰器左右?

I'm hoping to find something like: 我希望找到类似的东西:

for(Entry e : Collections.getDenormalizeEntriesFromMapOfCollection(myMap)) {
   System.out.println(e.getKey() + " - " + e.getValue());
}

That would give same result, just on the second situation you would have one entry for each key -> collection item. 这样会产生相同的结果,只是在第二种情况下,每个键都有一个条目 - >集合项。

I would recommend you to look at guavas MultiMap implementation. 我建议你看一下guavas MultiMap实现。 It already have this kind of iterator: 它已经有了这种迭代器:

To transform a Map<K, Collection<V> to a MultiMap<K, V> you can use a utility method: 要将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;
}

Usage: 用法:

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());
}

Outputs: 输出:

Hello=1
Hello=2
World=3

There is no more elegant way as the one you're using to iterate over a Map<String, List<String>> . 没有比你用来迭代Map<String, List<String>>更优雅的方式了。 But a more elegant thing to do would be to use a Guava ListMultimap , which provides an entries() method over which you can iterate directly, without a nested loop. 但更优雅的做法是使用Guava ListMultimap ,它提供了一个entries()方法,您可以在其上直接迭代,而不需要嵌套循环。

I think that Eclipse's debugger does exactly that, you can check out the implementation. 我认为Eclipse的调试器正是如此,你可以查看实现。 Otherwise you can write a helper method in an utility class for example since the Collections framework doesn't support this as far as I know. 否则,您可以在实用程序类中编写辅助方法,例如,因为据我所知,Collections框架不支持此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM