Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 885
sly7_7 Avatar asked Jun 22 '10 14:06

sly7_7


People also ask

How do you create a Multimap in Java?

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.

What is the difference between map and Multimap?

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.

Is there a Multimap in Java?

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).

How do you define Multimap?

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.


1 Answers

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()); } 
like image 105
Kevin Bourrillion Avatar answered Sep 28 '22 19:09

Kevin Bourrillion