How to compare two maps by their values

前端 未结 13 924
囚心锁ツ
囚心锁ツ 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:33

    The correct way to compare maps for value-equality is to:

    1. Check that the maps are the same size(!)
    2. Get the set of keys from one map
    3. For each key from that set you retrieved, check that the value retrieved from each map for that key is the same (if the key is absent from one map, that's a total failure of equality)

    In other words (minus error handling):

    boolean equalMaps(Mapm1, Mapm2) {
       if (m1.size() != m2.size())
          return false;
       for (K key: m1.keySet())
          if (!m1.get(key).equals(m2.get(key)))
             return false;
       return true;
    }
    

提交回复
热议问题