Home > Software design >  How to Inverse a Map with Duplicate Keys/Values
How to Inverse a Map with Duplicate Keys/Values

Time:01-08

I have a map with duplicate values and different keys. I want to reverse a map but want to retain the values associated to keys. It'll be more clear from below:

Original Map -

{key1=value1, key2=value1, key3=value2}

Expected Output -

{value1=key1, value1=Key2, value2=key3}
    Map<String, String> map = new HashMap<>();
    map.put("key1","value1");
    map.put("key2","value1");
    map.put("key3","value2");

    System.out.println(map);
    
    Map<String, String> inverseMap = MapUtils.invertMap(map); 
    System.out.println(inverseMap);

I am getting only {value1=key2, value2=key3} as duplicate keys are not allowed in maps. So is there any way get the expected output.

Thanks in Advance!

CodePudding user response:

you can't., keys cant be duplicates

1st you are assigning value1=key1

2n time when u assign value1= key2

"key1" is replaced by "key2"

CodePudding user response:

Picking up on @shmosel's idea of using Guava:

Multimap<String, String> inverseMap = ImmutableListMultimap.copyOf(map.entrySet()).inverse();
System.out.println(inverseMap);
System.out.println(inverseMap.entries());

This prints:

{value1=[key1, key2], value2=[key3]}
[value1=key1, value1=key2, value2=key3]

A Multimap is

A collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values.

  • Related