Search code examples
javaguavamultimap

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


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]}


Solution

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