Guava Multimap Guide

Multimap is one Map implementation from Google Guava library, maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values[1]:

  • a → 1, 2
  • b → 3

Maven Dependency

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

ArrayListMultimap

Create ArrayListMultimap

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.HashMultimap;

ArrayListMultimap<String, Integer> map = ArrayListMultimap.create();
map.put("a", 1);
map.put("a", 2);

System.out.println(map.get("a")); // output: [1, 2]

Now you have a ArrayListMultimap created, and under the key "a", it has two values: 1, 2.

ArrayListMultimap Loop

You can loop through ArrayListMultimap in multiple ways, but you should be aware of that by looping through keys, you would enter the same key multiple times, example:

/**
 * output: 
 * [1, 2]
 * [1, 2]
 */
for (String key : map.keys()) {
    System.out.println(map.get(key)); 
}

As the output shows, by map.keys(), we enter the same key two times, just as the number of values it contains.
But don't worry, there are ways to avoid this:

/**
 * output: 
 * [1, 2]
 */
for (String key : map.keySet()) {
    System.out.println(map.get(key));
}

/**
 * output: 
 * a->1
 * a->2
 */
for (Map.Entry<String, Integer> entry : map.entries()) {
    System.out.println(entry.getKey() + "->" + entry.getValue());
}

You can also just loop through values:

/**
 * output: 
 * 1
 * 2
 */
for (Integer value : map.values()) {
    System.out.println(value);
}

SetMultimap

SetMultimap is similar to ArrayListMultimap, except that it stores set type as values, not list.

import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;

SetMultimap<String, Integer> map = HashMultimap.create();
map.put("c", 1);
map.put("c", 1);
map.put("c", 2);
/**
 * output: 
 * c->1
 * c->2
 */
for (Map.Entry<String, Integer> entry : map.entries()) {
    System.out.println(entry.getKey() + "->" + entry.getValue());
}

References


  1. Guava Multimap ↩︎