Guava’s Multimap associates a key with multiple values.
If we have to do the traditional way it would be using Map<key, Collection<value>>
where Collection
can be an ArrayList
, a HashSet
, a TreeSet
etc.
In this article, we will see an example of Multimap using ArrayListMultimap
implementation. The main data structure is a HashMap
that uses an ArrayList
to store the values for a given key.
If we have to maintain Map<key, Collection<value>>
, we will be doing something like below:
Collection collection = map.get(key); if (collection == null) { collection = createCollection(key); map.put(key, collection); } collection.add(value));
We create using MultiMap
using code>ArrayListMultimap.
Multimap<String,String> bag = ArrayListMultimap.create();
We can add multiple values against the same key. For example, below we add multiple colors against ‘Color’ key and multiple furniture items against key ‘Furniture’.
bag.put(COLOR, RED); bag.put(COLOR, RED); bag.put(COLOR, YELLOW); bag.put(COLOR, GREEN); bag.put(COLOR, GREEN); bag.put(COLOR, GREEN); bag.put(FURNITURE, TABLE); bag.put(FURNITURE, CHAIR); bag.put(FURNITURE, SOFA);
ArrayListMultimap
allows duplicate key-value pairs.
We add ‘Red’ twice and ‘Green’ thrice.
We can get all the added items for a key using Multimap.get(key)
.
All the colors added can be obtained using the below:
bag.get(COLOR);
an the furniture items using:
bag.get(FURNITURE);
MultimapExample:
package com.javarticles.guava; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class MultimapExample { private static final String COLOR = "Color"; private static final String RED = "Red"; private static final String YELLOW = "Yellow"; private static final String GREEN = "Green"; private static final String FURNITURE = "Furniture"; private static final String TABLE = "Table"; private static final String CHAIR = "Chair"; private static final String SOFA = "Sofa"; public static void main(String[] args) { Multimap<String,String> bag = ArrayListMultimap.create(); bag.put(COLOR, RED); bag.put(COLOR, RED); bag.put(COLOR, YELLOW); bag.put(COLOR, GREEN); bag.put(COLOR, GREEN); bag.put(COLOR, GREEN); bag.put(FURNITURE, TABLE); bag.put(FURNITURE, CHAIR); bag.put(FURNITURE, SOFA); System.out.println("Total items in Bag: " + bag.size()); System.out.println("Total colors in Bag: " + bag.get(COLOR).size()); System.out.println("Colors in Bag: " + bag.get(COLOR)); System.out.println("Total items in furniture: " + bag.get(FURNITURE).size()); System.out.println("Furniture Items: " + bag.get(FURNITURE)); } }
Total items in the bag include even the duplicate items.
Output:
Total items in Bag: 9 Total colors in Bag: 6 Colors in Bag: [Red, Red, Yellow, Green, Green, Green] Total items in furniture: 3 Furniture Items: [Table, Chair, Sofa]
Download the source code
This was an example about Guava Multimap.