How to get key for value from Hashmap in Kotlin?

24,100

Solution 1

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

Solution 2

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.

Solution 3

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!

Share:
24,100
Asad Ali Choudhry
Author by

Asad Ali Choudhry

I have more than 5 years of experience in creating complex native mobile applications for iPhone and Android. I am adept in analyzing information, requirements, and system needs, evaluating end-user requirements, and developing solutions according to the needs. I am working in Dubai for the last 1.5 years and got diverse experience in development and team-leading. I can also work independently and can manage complex and big projects. I am also the co-founder of the website https://handyopinion.com/ where we share complex coding solutions with the young developers.

Updated on October 03, 2021

Comments

  • Asad Ali Choudhry
    Asad Ali Choudhry over 2 years

    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?