Comparing two hashmaps for equal values and same key sets?

153,145

Solution 1

Make an equals check on the keySet() of both HashMaps.

NOTE:

If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

Solution 2

Simply use :

mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings

Solution 3

Compare every key in mapB against the counterpart in mapA. Then check if there is any key in mapA not existing in mapB

public boolean mapsAreEqual(Map<String, String> mapA, Map<String, String> mapB) {

    try{
        for (String k : mapB.keySet())
        {
            if (!mapA.get(k).equals(mapB.get(k))) {
                return false;
            }
        } 
        for (String y : mapA.keySet())
        {
            if (!mapB.containsKey(y)) {
                return false;
            }
        } 
    } catch (NullPointerException np) {
        return false;
    }
    return true;
}

Solution 4

/* JAVA 8 using streams*/
   public static void main(String args[])
    {
        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        map.put(100, true);
        map.put(1011, false);
        map.put(1022, false);

        Map<Integer, Boolean> map1 = new HashMap<Integer, Boolean>();
        map1.put(100, false);
        map1.put(101, false);
        map1.put(102, false);

        boolean b = map.entrySet().stream().filter(value -> map1.entrySet().stream().anyMatch(value1 -> (value1.getKey() == value.getKey() && value1.getValue() == value.getValue()))).findAny().isPresent();
        System.out.println(b);
    }
Share:
153,145
membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on July 09, 2022

Comments

  • membersound
    membersound almost 2 years

    How can I best compare two HashMaps, if I want to find out if none of them contains different keys than the other, and if the values of that keys match each other.

    Map<objA, objB> mapA = new HashMap<objA, objB>();
    mapA.put("A", "1");
    mapA.put("B", "2");
    
    Map<objA, objB> mapB = new HashMap<objA, objB>();
    mapB.put("D", "4");
    mapB.put("A", "1");
    

    When comparing A with B, it should fail due to different keys B and D.

    How could I best compare non-sorted hashmaps?