How to create a Multimap<K,V> from a Map<K, Collection<V>>?
Solution 1:
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());
}
Solution 2:
This question is a little old, but I thought I'd give an updated answer. With Java 8 you could do something along the lines of
ListMultimap<String, String> multimap = ArrayListMultimap.create();
Map<String, Collection<String>> map = ImmutableMap.of(
"1", Arrays.asList("a", "b", "c", "c"));
map.forEach(multimap::putAll);
System.out.println(multimap);
This should give you {1=[a, b, c, c]}
, as desired.
Solution 3:
Here is a useful generic version that I wrote for my StuffGuavaIsMissing class.
/**
* Creates a Guava multimap using the input map.
*/
public static <K, V> Multimap<K, V> createMultiMap(Map<K, ? extends Iterable<V>> input) {
Multimap<K, V> multimap = ArrayListMultimap.create();
for (Map.Entry<K, ? extends Iterable<V>> entry : input.entrySet()) {
multimap.putAll(entry.getKey(), entry.getValue());
}
return multimap;
}
And an immutable version:
/**
* Creates an Immutable Guava multimap using the input map.
*/
public static <K, V> ImmutableMultimap<K, V> createImmutableMultiMap(Map<K, ? extends Iterable<V>> input) {
ImmutableMultimap.Builder<K, V> builder = ImmutableMultimap.builder();
for (Map.Entry<K, ? extends Iterable<V>> entry : input.entrySet()) {
builder.putAll(entry.getKey(), entry.getValue());
}
return builder.build();
}
Solution 4:
UPDATE: For what you're asking, I think you're going to need to fall back to Multimap.putAll
.