This post will discuss how to invert the mapping of a Map in Java. In order words, create a reverse map in Java.

1. Using for loop

You can use a simple for loop to create a reverse map. The idea is to create a new instance of Map<V,K> for a given map of type Map<K,V>. Then use a loop to iterate over the entries of the given map, and insert each entry into the new map in reverse order of its key-value pair.

The following code demonstrates this. Note that the code assumes that the inverse mapping is well-defined, and will fail for any repeated values in the given map. This can be easily handled by placing a conditional check before inserting a pair into the new map.

Download  Run Code

Output:

{1=A, 2=B, 3=C}

2. Using Stream API

We can do better in Java 8 and above, as demonstrated below:

Download  Run Code

Output:

{1=A, 2=B, 3=C}

 
Here’s another version using the Collectors.toMap() method, which helps accumulate the key-value pairs into a new Map.

Download  Run Code

Output:

{1=A, 2=B, 3=C}

 
Note that java.lang.IllegalStateException will be thrown if the values in the original map are not unique. This can be handled in two ways:

⮚ 1. Use a merge function

You can provide a merge function to merge values for the duplicate keys, where the old value can take precedence over the new value or vice versa.

Download  Run Code

Output:

{1=C, 2=B}

⮚ 2. Use groupingBy() function

Alternatively, you can use the groupingBy() collector to collect duplicate values into a List, resulting in a MultiMap.

Download  Run Code

Output:

{1=[A, C], 2=[B]}

3. Using Guava

If you have the Guava library in your project, you can get a bidirectional map BiMap and use its inverse() method. Note that the inverse() method results in a java.lang.IllegalArgumentException on encountering multiple entries with the same value.

Download Code

Output:

{1=A, 2=B, 3=C}

4. Using Apache Commons Collections

Like Guava library, Apache Commons Collections BidiMap interface, facilitate bidirectional lookups between key and values. To get an inverted bidirectional map, you can use the inverseBidiMap() method. It returns a view of the map where the keys and values are reversed.

Download Code

Output:

{1=A, 2=B, 3=C}

 
When multiple entries with the same value are found, the later key takes precedence over the former.

Download Code

Output:

{1=C, 2=B}

 
Apache Commons Collections also offers the MapUtils.invertMap() method, which returns a new HashMap with the keys of the given map swapped with the values. We should use this method only if the inverse mapping is well-defined. If the given map had the same value mapped to multiple keys, the returned map will contain one of those keys, but the exact key mapped is undefined.

Download Code

Output:

{1=A, 2=B, 3=C}

That’s all about inverting mapping of a Map in Java.