Asad Ali Choudhry
Asad Ali Choudhry

Reputation: 5261

How to get key for value from Hashmap in Kotlin?

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?

Upvotes: 32

Views: 52212

Answers (4)

Geraldo Neto
Geraldo Neto

Reputation: 4030

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!

Upvotes: 8

euclio
euclio

Reputation: 1487

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"

Upvotes: 12

canerkaseler
canerkaseler

Reputation: 7468

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.

Upvotes: 5

P.Juni
P.Juni

Reputation: 2485

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

Upvotes: 52

Related Questions