How to get Map’s key from value in Java

In this post, we will discuss how to get Map’s key from value in Java where there is 1:1 relationship between keys and values in the Map i.e. no two keys have same value.

 

1. entrySet() method

The idea is to iterate over all mappings present in the Map using entrySet() method and compare each value with the desired value until we get the corresponding key.

 

Download   Run Code

 
From Java 8, we can use Streams API:

 

Download   Run Code

 

2. keySet() 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 until we get the corresponding key.

 

Download   Run Code

 
From Java 8, we can use Streams API:

 

Download   Run Code

 

3. Create Reverse Map

The idea is extend HashMap class and overload its put() method such that it also inserts the value-key pair into a reverse map along with key-value pair in the original map. We also create a getKey() method that facilitates the value lookup in reverse map.

 

Download   Run Code

 

4. Guava BiMap

Guava provides BiMap class which is a bidirectional map to provide an inverse view of mappings i.e. with reversed keys and values. BiMap doesn’t allow duplicate values and throws IllegalArgumentException when multiple entries with same value is encountered. To get the inverse view of the BiMap, we can use inverse() method.

 

Download   Run Code

 

5. Apache Commons BidiMap

Similar to Guava, Apache Commons also facilitates bidirectional lookup between key and values by providing BidiMap interface. It has several implementations that allow a key to be looked up from a value using inverseBidiMap() method.

Please note that when multiple entries with same value is found, the last inserted key is returned.

 

Download

 

 
Follow-up: Retrieve all Map keys having given value in Java

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of