How to get key for value from Hashmap in Kotlin?

Viewed 31370

I have HashMap in Kotlin

val map = HashMap<String, String>()

I want to know how to get key for a particular value from this HashMap without iterating through complete HashMap?

4 Answers

Using filterValues {}

val map = HashMap<String, String>()
val keys = map.filterValues { it == "your_value" }.keys

And keys will be the set of all keys matching the given value

In Kotlin HashMap, you can use these ways:

val hashMap = HashMap<String, String>() // Dummy HashMap.

val keyFirstElement = hashMap.keys.first() // Get key.
val valueOfElement = hashMap.getValue(keyFirstElement) // Get Value.
    
val keyByIndex = hashMap.keys.elementAt(0) // Get key by index.
val valueOfElement = hashMap.getValue(keyByIndex) // Get value.

If you are constantly finding keys by values, a possible solution could be to reverse the map, so you can get any key by any value.

For instance:

val reversed = map.entries.associate{(k,v)-> v to k}

val resultKey = reversed[value]

Hope it helps!

In the worst case (if the matching value doesn't exist in the map), you'll have to iterate over the entire map. However, this code will stop iterating as soon as it finds a match:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

val matchingKey = map.entries.find { it.value == 3 }?.key

println(matchingKey) // prints "c"
Related