MultiKeyMap Implementation in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
internal class Key<K1, K2>(key1: K1, key2: K2) { private var key1: K1? = key1 private var key2: K2? = key2 override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null || javaClass != other.javaClass) { return false } val key = other as Key<*, *> if (if (key1 != null) key1 != key.key1 else key.key1 != null) { return false } return !if (key2 != null) key2 != key.key2 else key.key2 != null } override fun hashCode(): Int { var result = if (key1 != null) key1.hashCode() else 0 result = 31 * result + if (key2 != null) key2.hashCode() else 0 return result } override fun toString(): String { return "[$key1, $key2]" } } fun main() { val multiKeyMap: MutableMap<Key<*, *>, String> = HashMap() // [key1, key2] -> value1 val key1plus2: Key<*, *> = Key<Any?, Any?>("key1", "key2") multiKeyMap[key1plus2] = "value1" // [key3, key4] -> value2 val key3plus4: Key<*, *> = Key<Any?, Any?>("key3", "key4") multiKeyMap[key3plus4] = "value2" // print multikey map println(multiKeyMap) } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
data class Key<K1, K2>(val key1: K1, val key2: K2) { override fun toString(): String { return "[$key1, $key2]" } } fun main() { val multiKeyMap: MutableMap<Key<*, *>, String> = HashMap() // [key1, key2] -> value1 val key1plus2: Key<*, *> = Key<Any?, Any?>("key1", "key2") multiKeyMap[key1plus2] = "value1" // [key3, key4] -> value2 val key3plus4: Key<*, *> = Key<Any?, Any?>("key3", "key4") multiKeyMap[key3plus4] = "value2" // print multikey map println(multiKeyMap) } |
Output:
{[key1, key2]=value1, [key3, key4]=value2}
That’s all about MultiKeyMap implementation in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)