Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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. Any help would be greatly appreciated.

>Solution :

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())))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading