Search code examples
kotlinhashmap

Case insensitive key for hashmap kotlin?


I have a hashmap with string as key and integer as value. I want the keys to be case insensitive.

val items = HashMap<String, Int>()
    items["key1"] = 90
    items["Key1"] = 80
    items["C"] = 70
    for ((k, v) in items) {
        println("$k = $v")
    }

This takes key1 and Key1 as separate entries


Solution

  • For this, you would need either to provide some extension function that would put and get the entry in some defined way (e.g. using every time lowercase() String's method) keeping keys case insensitive

    fun HashMap<String, Int>.putInsensitive(k: String, v: Int) {
        this[k.lowercase()] = v
    }
    
    fun HashMap<String, Int>.getInsensitive(k: String, v: Int): Int? = this[k.lowercase()]
    

    or provide your own Map interface implementation (it could even inherit from HashMap)

    class InsensitiveHashMap<V> : HashMap<String, V>() {
        override fun put(key: String, value: V): V? = super.put(key.lowercase(), value)
        
        override fun get(key: String): V? = return super.get(key.lowercase())
    }