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.

Download Code

 
You can shorten the code using the filter() function:

Download Code

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.

Download Code

 
Alternatively, you can use lambda expressions to shorten the code and improve the code readability:

Download Code

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.

Download Code

That’s all about getting a map key from the value in Kotlin.