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).
Multimap
is an interface that is extended by its children interfaces: ListMultimap
and SetMultimap
. The standard way of creating a Multimap is to use the MultimapBuilder
class and specify the data structures that are to be used for the keys and values during building:
// create a ListMultimap with Integer keys in a hash table
// and String values in a LinkedList:
ListMultimap<Integer, String> m = MultimapBuilder.hashKeys().linkedListValues().build();
Another way to create a Multimap is to use the static method create()
in the concrete classes that implement the interface (e.g.,ArrayListMultimap<K, V>
, LinkedListMultimap<K, V>
, etc.):
ListMultimap<String, Integer> m = ArrayListMultimap.create();
All of the values associated with a key are retrieved in the form of a collection using Multimap.get(key)
; if that key does not exist in the Multimap, an empty collection is returned. The reference to the collection returned by this method can be used to modify the values for that key; these modifications will be reflected in the original Multimap.
A key-value pair can be added using Multimap.get(K).add(V)
, but it is more direct to use Multimap.put(K, V)
:
// Using returned collection to add values:
map.get(1).add("name");
// Direct method:
map.put(1, "name");
Similarly, a key-value pair can be removed from a Multimap indirectly or directly:
// Indirectly:
map.get(1).remove("name");
// Directly:
map.remove(1, "name");
A complete list of the available functions can be found in the official Guava documentation provided by Google.
Free Resources