Skip to main content

How do I map multiple values to a key

In this Q&A, we'll go over how to map multiple values to a key.

Map classes provides ability to map key to a value.  It does not provide the ability to map multiple values to a key.

Collection framework does not provide any other classes to achieve that.  One can map key to a collection of elements.  

As you'd expect, Guava and Apache Commons collection implementations provide that ability out of the box.  They provide classes that map a key to list or set of values.

Code snippet below has sample usage:

Guava

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>22.0</version>
</dependency>

Multimap<Integer, Integer> mm = ArrayListMultimap.create();
IntStream.range(1,100).forEach( (i) -> {mm.put(i, i); mm.put(i, i+1); });
Collection<Integer> ai = mm.get(1);
assertThat(ai).containsExactly(1, 2);

Commons

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
map.put("a", "b");
map.put("a", "c");
Collection<String> c =  map.get("a");
assertThat(c).containsExactly("b", "c");

Comments