Skip to content
Advertisement

Mapping duplicate values from Map against the keys in which they are found [closed]

What I have is:

Map<String, String> map = new HashMap<>();
map.put("Shop1", "Product1");
map.put("Shop2", "Product2");
map.put("Shop3", "Product1");
map.put("Shop4", "Product2");
map.put("Shop5", "Product3");

What I want is:

Map<String, List<String>> result = new HashMap<>();

Wherein result contains:

Product1 -> Shop1,Shop3

Product2 -> Shop2,Shop4

Here Product1 is found at multiple times in shops Shop1 & Shop3 and Product2 is found multiple times in shops Shop2 & Shop4.

Advertisement

Answer

What you’re trying to do is to invert the map (values become keys and keys get grouped by old values). There should be libraries that do that, but a sample solution with streams:

result = map.entrySet()
.stream()
.filter(e -> Collections.frequency(map.values(), e.getValue()) > 1)
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement