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
?
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.
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 .
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With