Start learning free

LESSON 228 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a Dictionary in Java: Swapping HashMap Keys and Values

Practice Read the full explanation

Given a HashMap d whose keys and values are strings, return a new HashMap with the keys and values swapped: every value of d becomes a key, and it maps to the key it belonged to.

The order of the entries in the HashMap you return doesn't matter.

Example 1:

Input: d = {"apple": "red", "banana": "yellow", "plum": "purple"}
Output: {"red": "apple", "yellow": "banana", "purple": "plum"}
Explanation: "apple" mapped to "red", so now "red" maps to "apple". The other two entries turn around the same way.

Example 2:

Input: d = {"cat": "dog"}
Output: {"dog": "cat"}
Explanation: One entry gives one entry, turned around.

Example 3:

Input: d = {"a": "b", "b": "c"}
Output: {"b": "a", "c": "b"}
Explanation: "b" is both a key and a value of d. As the value of "a", it becomes a key that maps to "a". As a key, its entry "b": "c" turns into "c": "b".

Rules:

  • d has at least one entry.
  • All the values of d are different, so the result has as many entries as d.
  • Keys and values are words without spaces.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in Java, explained

    Problem overview

    The method invertDictionary receives a HashMap<String, String> named d and returns a new map with keys and values swapped. Every value of d becomes a key, and it maps to the key it belonged to.

    With {"apple": "red", "banana": "yellow", "plum": "purple"} the result is {red=apple, yellow=banana, purple=plum}. With {"cat": "dog"} it is {dog=cat}. The lesson promises that all values of d are different, so the result has as many entries as d. The order of the entries doesn't matter.

    A map can use the same string as a key and as a value. In {"a": "b", "b": "c"}, "b" is the value of "a" and also a key. Inverted, the entry a=b becomes b=a, and the entry b=c becomes c=b. The result is {b=a, c=b}. The two roles of "b" don't interfere, because the result is a separate, new map.

    Approach: turn each entry around into a new map

    Read one entry at a time and write its mirror image into a fresh map. A key and its value are two halves of one entry, so you need both while you work. Writing into a new map, instead of changing d while looping over it, keeps the loop safe: changing a map during iteration over its keys makes Java throw a ConcurrentModificationException.

    Step by step

    1. Create the empty result. HashMap<String, String> result = new HashMap<>(); receives the swapped pairs.
    2. Loop over the keys. d.keySet() returns the keys, and the enhanced for loop visits each as a String key.
    3. Read the value with d.get(key) into a String value. The key exists, because it came from the map, so get never returns null here.
    4. Store the swapped pair: result.put(value, key). The old value is the new key, and the old key is the new value.
    5. Return result after the loop.

    The solution in Java

    class Solution {
        public HashMap<String, String> invertDictionary(HashMap<String, String> d) {
            HashMap<String, String> result = new HashMap<>();
            for (String key : d.keySet()) {
                String value = d.get(key);
                result.put(value, key);
            }
            return result;
        }
    }
    

    Java details worth knowing:

    • keySet() and the order. A HashMap visits its keys in an order of its own, so the loop can handle the entries in any order. It doesn't matter here, because each entry is independent.
    • A shorter loop. for (Map.Entry<String, String> e : d.entrySet()) gives the key and the value together with getKey() and getValue(), so no get call is needed. The lesson's version uses get because it shows each step plainly.
    • Distinct values matter. If two keys shared a value, the second put would overwrite the first and one entry would be lost. With {"a": "x", "b": "x"} the inverse has a single entry, and which key survives depends on the iteration order. The lesson rules this out.
    • The original is untouched. d is only read, so it keeps its entries after the call.

    Complexity

    Time: O(n) for n entries: each costs one get and one put, both constant on average. Space: O(n), since the new map has as many entries as d.

    Edge cases and common mistakes

    • Calling put(key, value) by habit. That copies the map instead of inverting it. The value goes first.
    • Modifying d inside the loop. Adding or removing keys of the map being iterated throws a ConcurrentModificationException.
    • A value that is also a key. It needs no special handling, as the {"a": "b", "b": "c"} example shows.
    • Duplicate values. They lose entries. If a lesson allowed them, the inverse would need a list as its value type.

    Testing

    • {"apple": "red", "banana": "yellow", "plum": "purple"} gives {red=apple, yellow=banana, purple=plum}.
    • {"cat": "dog"} gives {dog=cat}.
    • {"a": "b", "b": "c"} gives {b=a, c=b}.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free