Get a key from specific value in Kotlin Map
This article explores different ways to get a key from a specified value in Kotlin Map. Assume no two keys have the same value.
1. Using entries property
The standard way is to iterate over all key/value pairs using the entries property and compare each encountered value with the provided value until you get the corresponding key.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
fun <K, V> getKey(map: Map<K, V>, target: V): K? { for ((key, value) in map) { if (target == value) { return key } } return null } fun main() { val map: MutableMap<String?, Int?> = HashMap() map["A"] = 1 map["B"] = 2 map["C"] = 3 println(getKey(map, 2)) // output: 'B' } |
You can shorten the code using the filter() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <K, V> getKey(hashMap: Map<K, V>, target: V): K { return hashMap.filter { target == it.value }.keys.first() } fun main() { val map: MutableMap<String?, Int?> = HashMap() map["A"] = 1 map["B"] = 2 map["C"] = 3 println(getKey(map, 2)) // output: 'B' } |
2. Using keys property
You can also iterate over all keys using the keys property and compare each key’s value with the provided value until you get the corresponding key.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun <K, V> getKey(map: Map<K, V>, target: V): K? { for (key in map.keys) { if (target == map[key]) { return key } } return null } fun main() { val map: MutableMap<String?, Int?> = HashMap() map["A"] = 1 map["B"] = 2 map["C"] = 3 println(getKey(map, 2)) // output: 'B' } |
Alternatively, you can use lambda expressions to shorten the code and improve the code readability:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <K, V> getKey(map: Map<K, V>, target: V): K { return map.keys.first { target == map[it] }; } fun main() { val map: MutableMap<String?, Int?> = HashMap() map["A"] = 1 map["B"] = 2 map["C"] = 3 println(getKey(map, 2)) // output: 'B' } |
3. Using Reverse Map
Another plausible solution is to extend the HashMap class and overload its put() function such that it inserts the value/key pair into a reverse map along with the key/value pair in the original map.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
internal class MyHashMap<K, V> : HashMap<K, V?>() { private var rMap: MutableMap<V?, K> = HashMap() override fun put(key: K, value: V?): V? { rMap[value] = key return super.put(key, value) } fun getKey(target: V): K? { return rMap[target] } } fun main() { val map: MyHashMap<String, Int> = MyHashMap() map["A"] = 1 map["B"] = 2 map["C"] = 3 println(map.getKey(2)) // output: 'B' } |
That’s all about getting a map key from the value in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)