This post will implement MultiKeyMap in plain Java and cover its possible implementations in Apache Commons Collection and Guava library. Basically, we need a map implementation that uses multiple keys to map the value in Java.

1. Using Plain Java

The idea is to construct a custom class Key, which consists of all keys, and use an instance of the Key class in our map as a key to map the value. The Key class should override equals() and hashCode() methods to test equality on hash-based map. This is demonstrated below for two keys. Note that we can easily extend the solution to any number of keys.

Download  Run Code

Output:

{[key1, key2]=value1, [key3, key4]=value2}
value1

2. Using Apache Commons Collections

We can also use Apache Commons Collection, which provides an efficient map implementation MultiKeyMap that maps multiple keys to a value. MultiKeyMap provides get, containsKey, put, and remove for individual keys.

Download Code

Output:

{MultiKey[key1, key2]=value1, MultiKey[key3, key4]=value2}
value1

3. Using Google’s Guava

There are several ways to accomplish this with Google’s Guava library. An elegant solution is to use Guava’s Table interface, which associates an ordered pair of keys, called a row key and a column key, with a single value.

Download Code

Output:

{key1={key2=value1}, key3={key4=value2}}
value1

 
We can also use ImmutableList to build your keys in order, as shown below:

Download Code

Output:

{[key1, key2]=value1, [key3, key4]=value2}
value1

That’s all about MultiKeyMap implementation in Java.