MultiKeyMap is a map implementation that uses multiple keys to map the value. This post will provide MultiKeyMap implementation in Kotlin.

The idea is to construct a class that consists of all keys and uses an instance of that class in our map as a key to map the value. The class should override equals() and hashCode() methods to test equality on a hash-based map.

 
This approach is demonstrated below for two keys, but we can easily extend it to an arbitrary number of keys.

Download Code

 
Output:

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

 
Kotlin’s data class already provides an implementation of equals() and hashCode() methods. The following example shows usage of data class to implement a MultiKeyMap:

Download Code

 
Output:

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

That’s all about MultiKeyMap implementation in Kotlin.