Kotlin - Map with Multiple Keys - Example
Today we will show you how to implement a Map with Multiple Keys.
- Solution 1: Using Kotlin Custom Key Class
- Solution 2: Using Google's Guava
- Solution 3: Using Apache Commons Collections
Example 1: Using Kotlin Custom MultiMapKey
Here we created a custom MultiMap Key class, we can use MultiMap as a Key to map a value.
object MultiKeyDemo {@JvmStaticfun main(args: Array<String>) {// Declaring the Mapval table: MutableMap<MultiMapKey, String> = HashMap()// Declaring the key objectsval key1 = MultiMapKey("raw1", "col1")val key2 = MultiMapKey("raw1", "col2")val key3 = MultiMapKey("raw1", "col3")// Putting the valuestable[key1] = "Java"table[key2] = "Kotlin"table[key3] = "Android"// Getting value by keyval value2 = table[key2]println(value2)// Iterate maptable.forEach { (k: MultiMapKey, v: String) ->println("Key = "+ k + ", Value = " + v)}// Remove one itemtable.remove(key2)}}internal class MultiMapKey(var row: Any, var col: Any) {override fun hashCode(): Int {return row.hashCode() xor col.hashCode()}override fun equals(myKey: Any?): Boolean {return if (myKey is MultiMapKey) {val multiMapKey = myKeyrow == multiMapKey.row && col == multiMapKey.col} else {false}}}
Example 2: Using Google's Guava
Guava's Table is a collection that represents a table-like structure containing rows, columns and the associated cell values. The row and the column act as an ordered pair of keys.
import com.google.common.collect.HashBasedTable
import com.google.common.collect.Table
object GuavaMultiKeyDemo {
@JvmStatic
fun main(args: Array<String>) {
// Declaring the Table
val table: Table<String, String, String> = HashBasedTable.create()
// Insert & Update
table.put("raw1", "col1", "Java")
table.put("raw1", "col2", "Kotlin")
table.put("raw1", "col3", "Android")
// Getting the values
val value2 = table["raw1", "col3"]
println(value2)
}
}
Example 3: Using Apache Commons Collection
The MultiKeyMap is the most efficient way to use multiple keys to map to a value. These provide get, containsKey, put and remove for individual keys which operate without extra object creation.
import org.apache.commons.collections4.map.MultiKeyMap
object ApacheMultiKeyDemo {
@JvmStatic
fun main(args: Array<String>) {
// Declaring the MultiKeyMap
val table = MultiKeyMap<String, String>()
// Insert & Update
table.put("raw1", "col1", "Java")
table.put("raw1", "col2", "Kotlin")
table.put("raw1", "col3", "Android")
// Getting the values
val value2 = table["raw1", "col2"]
println(value2)
// Contains key
val containsKey = table.containsKey("raw1", "col1")
println(containsKey)
}
}