Retrieve all Map keys having given value in Java

In this post, we 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. entrySet() method

We can also iterate over all entries present in the Map using entrySet() method and insert all keys that satisfies the criteria into a Set.

 

Download   Run Code

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

 

Download   Run Code

 

3. keySet() method

Similar to the entrySet() method, we can also iterate over all keys present in the Map using 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

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of