Iterating over List in a Map

collections, java

Solution

I would recommend you to look at guavas `MultiMap` implementation. 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:

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

Problem

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.

Original source