This article explores different ways to retrieve all keys with the specified value in Kotlin Map.

1. Create a Reverse Map

The trick is to extend the HashMap class and overload its put() function in such a way that every call to put inserts the key/value pair into the original map and the value-key pair to a reverse map.

Download Code

2. Using entries property

Another solution is to iterate over all entries present in the Map and insert all keys that satisfy the criteria into a collection.

Download Code

 
The code can be shortened using the filter() function with the keys property:

Download Code

3. Using keys property

Another solution is to iterate over all keys present in the Map using the keys property and compare each key with the desired value. The matching keys are then inserted into a collection.

Download Code

 
Alternatively, you can call the filter() function on the Set returned by the keys property:

Download Code

That’s all about retrieving all keys with the specified value in Kotlin Map.