How to Invert a Map in Java

06 May 2023 Balmiki Mandal 0 Core Java

How to Invert a Map in Java

Inverting a Map in Java can be a difficult task. The process involves using a loop to iterate over the entries in the map and creating new entries with the key and value swapped around. This guide will show you how to invert a Map using Java.

Step 1: Create a New Map

To begin, we will need to create a new Map to store our inverted entries. Since Java does not natively support maps with more than one key for each value, we will instead create a Map of Lists, where the keys are the values from the original Map, and the values are the lists of keys that correspond to that value.

Map<Object, List> invertedMap = new HashMap<>();


Step 2: Iterate Over the Existing Map

Next, we need to iterate over each entry in the original map. We can do this using a for-each loop.

for (Map.Entry<Object, Object> entry : map.entrySet()) {
    // code goes here
}

Step 3: Add Entries to the new Map

Inside the loop, we need to add an entry to the new map. First, we need to check if the key exists in the new map. If it doesn't, we need to create a new list and add the key to it. Otherwise, we just add the key to the existing list.

List keys = invertedMap.get(entry.getValue());
if (keys == null) {
    keys = new ArrayList<>();
    keys.add(entry.getKey());
    invertedMap.put(entry.getValue(), keys);
} else {
    keys.add(entry.getKey());
}

Step 4: Test the Output

Now we can test the output by printing the contents of the new map. Assuming the original map contained the following entries:

{"Foo" : "Bar",
"Baz" : "Qux",
"Quux" : "Bar"}

The resulting inverted map should look like this:

{"Bar" : ["Foo", "Quux"],
"Qux" : ["Baz"]}

And that's it! With just a few lines of code, we have successfully inverted a Map in Java.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.