Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Understanding Apache MultiKeyMap

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

Ganesh Kumar Marimuthu
Nerd For Tech
Published in
3 min readJul 1, 2021

--

Photo by Chunli Ju on Unsplash

Overview

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.

MultiKeyMap

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

Conclusion

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

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Ganesh Kumar Marimuthu
Ganesh Kumar Marimuthu

Written by Ganesh Kumar Marimuthu

SDE II at Amazon. ✍️ Content Writer 🔸 👨‍💻 Full Stack Engineer

No responses yet