Guava provides a Multimap interface that allows mapping of a single key to multiple values in Java. This post will discuss 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>>. We might often want to use a third-party library for Multimap in Java, such as Guava. There are several ways to convert a Map<K, Collection<V>> to Guava’s Multimap:

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

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

Download  Run Code

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

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

Download  Run Code

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

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

Download  Run Code

4. Using Map.forEach() with 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 an immutable multimap instance with the help of a builder.

Download  Run Code

That’s all about converting a Map<K, Collection<V>> to Guava’s Multimap in Java.