Convert a Map<K, Collection<V>> to Guava’s Multimap in Java

Guava provides a Multimap interface that allows mapping of a single key to multiple values in Java. In this post, we will see how to convert a Map<K,Collection<V>> to Guava’s Multimap in Java.


We can create our own custom implementation of Multimap in Java using a Map and a Collection by implementing the map as Map<K,Collection<V>>. But often we might want to use a third party library for Multimap in Java such a Guava, there any several ways to convert a Map<K,Collection<V>> to Guava’s Multimap


1. Using Map.entrySet() + ListMultimap.put() method

Naive solution is to iterate over the mappings contained in map using Map.entrySet() and for each value in a mapping, use ListMultimap.put() method to insert that key-value pair in the multimap.


Download   Run Code


2. Using Map.entrySet() + ListMultimap.putAll() method

Instead of using ListMultimap.put() method to insert key-value pairs in the multimap one by one, we can use ListMultimap.putAll() method to insert all values mapped to a particular key all at once.


Download   Run Code


3. Using Map.keySet() + ListMultimap.putAll() method

Another alternative is to use Map.keySet() to iterate over the keys contained in the map and for each key, use ListMultimap.putAll() method to insert key-value pair in the multimap.


Download   Run Code


4. Java 8 – Using Map.forEach() + ListMultimap.putAll() method

In Java 8, we can use Map.forEach() to iterate over each mapping in the map and pass method reference to ListMultimap.putAll() as argument to forEach().


Download   Run Code


5. Creating an Immutable Multimap

Guava also provides Immutable Multimap whose contents can never change. We can use similar logic as discussed above to construct a immutable multimap instance with the help of builder.


Download   Run Code

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

Notify of