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]}
Following is a simple custom implementation of the Multimap class in Java using a Map and a Collection . * Add the specified value with the specified key in this multimap. * Returns the Collection of values to which the specified key is mapped, * or null if this multimap contains no mapping for the key.
The map and the multimap are both containers that manage key/value pairs as single components. The essential difference between the two is that in a map the keys must be unique, while a multimap permits duplicate keys.
A Multimap is a new collection type that is found in Google's Guava library for Java. A Multimap can store more than one value against a key. Both the keys and the values are stored in a collection, and considered to be alternates for Map<K, List<V>> or Map<K, Set<V>> (standard JDK Collections Framework).
In computer science, a multimap (sometimes also multihash, multidict or multidictionary) is a generalization of a map or associative array abstract data type in which more than one value may be associated with and returned for a given key.
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With