Understanding Apache MultiKeyMap

A data structure to store values with multiple keys in a map

Subscribe to my newsletter and never miss my upcoming articles

Photo by Chunli Ju on Unsplash


HashMap is a wonderful data structure that stores data in the form of Key-Value pairs that provide insert, update, retrieve, and delete operations in O(1) time.

HashMap has one limitation that it can have only one key. But wait. Why do we need multiple keys for a single value? Let us look at an example.

Suppose we want to look up the marks of a student by Student, Exam, and Subject. The typical solution is to create a Nested Map like below.

Implementation using Nested Map

But look how complex the code is. It may get even complex with a large number of keys. This can be solved using MultiKeyMap. It comes as part of Apache’s commons-collections4 package.


Now let us implement the above feature using MultiKeyMap.

Insert Values to MultiKeyMap

Implementation using MultiKeyMap

In the above code, the first 3 parameters of the put method are keys and the last parameter is the value.

Iterate a MultiKeyMap

MultiKeyMap can be easily iterated using forEach iterator.

Iterate a MultiKeyMap

Look at the output of the above code. All the keys are stored as MultiKey, a data structure provided by the Apache commons-collections library. This is how all the keys are stored internally.

Delete Values from MultiKeyMap

Values can be deleted from MultiKeyMap using a single key or multiple keys.

Delete values from a MultiKeyMap

The entire code can be downloaded from the below gist



MultiKeyMap comes in handy when we have to look up using more than one key. MultiKeyMap also comes with a limitation in that it supports a maximum of 5 keys. The library can be downloaded from the official Maven Repository.

Thank you 🤘

To know more about me, visit ganeshkumarm.me

Understanding Apache MultiKeyMap was originally published in Nerd For Tech on Medium, where people are continuing the conversation by highlighting and responding to this story.

No Comments Yet