This post will discuss how to retrieve all map keys having given value in Java.

1. Create Reverse Map

The idea is to decorate the map with our own implementation by extending the HashMap class and overloading its put() method such that for every call to the put method, it not only inserts the key-value pair in the original map but also inserts the value-key pair into a reverse map.

Download  Run Code

2. Using entrySet() method

We can also iterate over all entries present in the map using the entrySet() method and insert all keys that satisfy the criteria into a set.

Download  Run Code

 
In Java 8 and above, we can do something like:

Download  Run Code

3. Using keySet() method

Like the entrySet() method, we can also iterate over all keys present in the map using the keySet() method and compare each key’s value with the desired value.

Download  Run Code

 
In Java 8 and above, we can do something like:

Download  Run Code

That’s all about retrieving all Map keys having a given value in Java.