How to compare two maps by their values

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

    To see if two maps have the same values, you can do the following:

    • Get their Collection values() views
    • Wrap into List
    • Collections.sort those lists
    • Test if the two lists are equals

    Something like this works (though its type bounds can be improved on):

    static >
    boolean valuesEquals(Map map1, Map map2) {
        List values1 = new ArrayList(map1.values());
        List values2 = new ArrayList(map2.values());
        Collections.sort(values1);
        Collections.sort(values2);
        return values1.equals(values2);
    }
    

    Test harness:

    Map map1 = new HashMap();
    map1.put("A", "B");
    map1.put("C", "D");
    
    Map map2 = new HashMap();
    map2.put("A", "D");
    map2.put("C", "B");
    
    System.out.println(valuesEquals(map1, map2)); // prints "true"
    

    This is O(N log N) due to Collections.sort.

    See also:

    • Collection values()

    To test if the keys are equals is easier, because they're Set:

    map1.keySet().equals(map2.keySet())
    

    See also:

    • Set keySet()

提交回复
热议问题