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

1. Using entrySet() method

The idea is to iterate over all mappings present in the map using the 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 Stream:

Download  Run Code

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

Download  Run Code

 
From Java 8, we can use Stream:

Download  Run Code

3. Using Reverse Map

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

Download  Run Code

4. Using Guava’s BiMap Class

Guava provides a BiMap class, 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 the same value are encountered. To get the inverse view of the BiMap, we can use the inverse() method.

Download Code

5. Using Apache Commons Collections

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

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

Download Code

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

 
Follow-up:

Retrieve all Map keys having given value in Java