Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two Maps and remove all the elements that either have the same key or the same value

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?

like image 470
Kathy Avatar asked Oct 26 '25 10:10

Kathy


2 Answers

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!

like image 167
tumisma Avatar answered Oct 28 '25 23:10

tumisma


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}

like image 37
Thanga Avatar answered Oct 28 '25 22:10

Thanga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!