I have a hashmap with some keys pointing to same values. I want to find all the values that are equal and print the corresponding keys.
This is the current code that I
If you want a solution beside to Stream API;
public static void duplicatedValuesMap() {
Map map = new HashMap<>();
map.put("hello", "0123");
map.put("hola", "0123");
map.put("kosta", "0123 test");
map.put("da", "03");
map.put("notda", "013");
map.put("twins2", "01");
map.put("twins22", "01");
HashMap> valueToKeyMapCounter = new HashMap<>();
for (Map.Entry entry : map.entrySet()) {
if (valueToKeyMapCounter.containsKey(entry.getValue())) {
valueToKeyMapCounter.get(entry.getValue()).add(entry.getKey());
} else {
List keys = new ArrayList<>();
keys.add(entry.getKey());
valueToKeyMapCounter.put(entry.getValue(), keys);
}
}
for (Map.Entry> counterEntry : valueToKeyMapCounter.entrySet()) {
if (counterEntry.getValue().size() > 1) {
System.out.println("Duplicated Value:" + counterEntry.getKey() + " for Keys:" + counterEntry.getValue());
}
}
}