Home > Software design >  Compare two hashmaps and remove duplicates from second hashmap
Compare two hashmaps and remove duplicates from second hashmap

Time:02-23

HashMap<Double, Date> hm1 = new HashMap<Double, Date>();
HashMap<Double, Date> hm2 = new HashMap<Double, Date>();

hm1.put(11, Wed Feb 23 12:56:24 IST 2022);
hm1.put(12, Wed Feb 23 12:56:48 IST 2022);
hm1.put(13, Wed Feb 23 12:56:45 IST 2022);
hm1.put(14, Wed Feb 23 12:56:51 IST 2022);
hm1.put(15, Wed Feb 23 12:56:50 IST 2022);

hm2.put(11, Wed Feb 23 12:56:24 IST 2022);
hm2.put(12, Wed Feb 23 12:56:48 IST 2022);
hm2.put(13, Wed Feb 23 12:56:45 IST 2022);
hm2.put(17, Wed Feb 23 12:56:37 IST 2022);
hm2.put(18, Wed Feb 23 12:56:28 IST 2022);

Need to compare these two hashmaps and get output as hashmap which contains the filtered entries from hm2 i.e remove duplicates after comparing with hm1

output should be

hm2 = {17=Wed Feb 23 12:56:37 IST 2022,
18=Wed Feb 23 12:56:28 IST 2022}

CodePudding user response:

If key and value must be the same in order to qualify as a duplicate it would be something like:

    Map<Integer, String> hm1 = new HashMap<Integer, String>();
    Map<Integer, String> hm2 = new HashMap<Integer, String>();

    hm1.put(11, "Wed Feb 23 12:56:24 IST 2022");
    hm1.put(12, "Wed Feb 23 12:56:48 IST 2022");
    hm1.put(13, "Wed Feb 23 12:56:45 IST 2022");
    hm1.put(14, "Wed Feb 23 12:56:51 IST 2022");
    hm1.put(15, "Wed Feb 23 12:56:50 IST 2022");

    hm2.put(11, "Wed Feb 23 12:56:24 IST 2022");
    hm2.put(12, "Wed Feb 23 12:56:48 IST 2022");
    hm2.put(13, "Wed Feb 23 12:56:45 IST 2022");
    hm2.put(17, "Wed Feb 23 12:56:37 IST 2022");
    hm2.put(18, "Wed Feb 23 12:56:28 IST 2022");

    //removing duplicates
    for (Integer key : hm1.keySet()) {
        if (hm2.containsKey(key)) {
            if (hm1.get(key).equals(hm2.get(key))) {
                hm2.remove(key);
            }
        }
    }
    
    // show content of hm2
    System.out.println(hm2);
    

}

If only the key is relevant to qualify as a duplicate use

for (Integer key : hm1.keySet()) {
     hm2.remove(key);           
}

instead of

for (Integer key : hm1.keySet()) {
        if (hm2.containsKey(key)) {
            if (hm1.get(key).equals(hm2.get(key))) {
                hm2.remove(key);
            }
        }
    }

CodePudding user response:

Use the remove method which accepts two params (key and value).

Removes the entry for the specified key only if it is currently mapped to the specified value.

So in your case:

hm1.forEach((k,v) -> hm2.remove(k,v));
  • Related