How to compare two maps by their values

前端 未结 13 949
囚心锁ツ
囚心锁ツ 2020-12-08 12:09

How to compare two maps by their values? I have two maps containing equal values and want to compare them by their values. Here is an example:

    Map a = ne         


        
13条回答
  •  无人及你
    2020-12-08 12:46

    This question is old, but still relevant.

    If you want to compare two maps by their values matching their keys, you can do as follows:

    public static  boolean mapEquals(Map leftMap, Map rightMap) {
        if (leftMap == rightMap) return true;
        if (leftMap == null || rightMap == null || leftMap.size() != rightMap.size()) return false;
        for (K key : leftMap.keySet()) {
            V value1 = leftMap.get(key);
            V value2 = rightMap.get(key);
            if (value1 == null && value2 == null)
                continue;
            else if (value1 == null || value2 == null)
                return false;
            if (!value1.equals(value2))
                return false;
        }
        return true;
    }
    

提交回复
热议问题