I have two Maps that I need to compare and merge them into a result map. I need to remove all the elements that either have the same key or the same value.
Basically, say I have two Maps:
Map<String, String> map1 = new HashMap<>();
map1.put("1", "A");
map1.put("2", "A");
map1.put("3", "B");
map1.put("4", "C");
map1.put("5", "D");
map1.put("6", "E");
Map<String, String> map2 = new HashMap<>();
map2.put("1", "B");
map2.put("2", "A");
map2.put("4", "F");
map2.put("6", "C");
map2.put("7", "G");
map2.put("8", "H");
I need to remove all the entries that have either the same keys or the same values and need to retain back only bidirectional unique entries. So after merge, I need to have the following result map in which every key maps to a unique value and every value has a unique key:
("5", "D"), ("7", "G"), ("8", "H")
What's the best way to do this in Java?
I would create another map that contains all the values and keys from map1 and map2, and then I would go through a loop deleting the duplicates keys and values
Map<String, String> map3 = new HashMap<>();
map3.putAll(map1);
map3.putAll(map2);
for(String a: map1.keySet()){
if(map2.containsKey(a) || map2.containsValue(map1.get(a))){
map3.remove(a);
}
}
Hope this is useful!
Below code will do this
Map map3 = new HashMap<>(map1);
map3.keySet().removeAll(map2.keySet());
map3.values().removeAll(map2.values());
map2.keySet().removeAll(map1.keySet());
map2.values().removeAll(map1.values());
map3.putAll(map2);
System.out.println(map3);
This will result {7=G, 5=D, 8=H}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With