Inverse a Map with Duplicates Using Loop in Java

Viewed 29

I want to inverse a map with duplicate values by using only loop method. What should be the logic that I should use inside loop?

    Map<String, Integer> hashMap = new HashMap<>();
    hashMap.put("A", 1);
    hashMap.put("B", 2);
    hashMap.put("C", 2);

    Map<Integer, String> inverseMap = new HashMap<>();
    for (Map.Entry<String, Integer> entry : hashMap.entrySet()){
        inverseMap.put(entry.getValue(), entry.getKey());
    }

    System.out.println(inverseMap);

Input: {A=1, B=2, C=2}

Desired Output: {1=A, 2=B, 2=C}

0 Answers
Related