Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
Asad Ali Choudhry Avatar asked Jun 10 '19 08:06

Asad Ali Choudhry


People also ask

How do I get the key for HashMap in Kotlin?

Kotlin HashMap getget() method. getOrElse() method that returns default value if there is no value for the key. getOrPut() method that returns default value if there is no value for the key, and put the entry with key and default value to the HashMap.

How do you access map values in Kotlin?

For retrieving a value from a map, you must provide its key as an argument of the get() function. The shorthand [key] syntax is also supported. If the given key is not found, it returns null .


2 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

like image 119
P.Juni Avatar answered Sep 19 '22 09:09

P.Juni


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.
like image 28
DevPolarBear Avatar answered Sep 21 '22 09:09

DevPolarBear