How to create a Multimap<K,V> from a Map<K, Collection<V>>?

sly7_7 picture sly7_7 · Jun 22, 2010 · Viewed 76.6k times · Source

I didn't find such a multimap construction... When I want to do this, I iterate over the map, and populate the multimap. Is there an other way?

final Map<String, Collection<String>> map = ImmutableMap.<String, Collection<String>>of(
            "1", Arrays.asList("a", "b", "c", "c"));
System.out.println(Multimaps.forMap(map));

final Multimap<String, String> expected = ArrayListMultimap.create();
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
    expected.putAll(entry.getKey(), entry.getValue());
}
System.out.println(expected);

The first result is {1=[[a, b, c, c]]} but I expect {1=[a, b, c, c]}

Answer

Kevin Bourrillion picture Kevin Bourrillion · Jun 23, 2010

Assuming you have

Map<String, Collection<String>> map = ...;
Multimap<String, String> multimap = ArrayListMultimap.create();

Then I believe this is the best you can do

for (String key : map.keySet()) {
  multimap.putAll(key, map.get(key));
}

or the more optimal, but harder to read

for (Entry<String, Collection<String>> entry : map.entrySet()) {
  multimap.putAll(entry.getKey(), entry.getValue());
}