'Compare HashMap Values structured as List [closed]
I have a HashMap structured like
{a=[test], b=[test, test2]}
I want to compare entry values (test, test2) with each other and if any entry has same value with another one, I need to return their keys and the equal value. I want to do this in Java.
Solution 1:[1]
Simply reverse the Map, use your values as grouping key for the original keys where the value repeat.
Map<KeysClass, List<ValuesClass>> original = ....
Map<ValuesClass, List<KeysClass>> keysGroupedPerValue = new HashMap<>();
for(Entry<KeysClass, List<ValuesClass> entry : original) {
for(ValuesClass value : entry.getValue()) {
List<KeysClass> keysHavingValue = keysGroupedPerValue.computeIfAbsent(value, val -> new ArrayList<>());
keysHavingValues.add(entry.getKey());
}
}
There are also more elegant solutions using the Stream and Collector APIs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Baptiste Beauvais |
