How to compare two maps by their values

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

    If you assume that there can be duplicate values the only way to do this is to put the values in lists, sort them and compare the lists viz:

    List values1 = new ArrayList(map1.values());
    List values2 = new ArrayList(map2.values());
    Collections.sort(values1);
    Collections.sort(values2);
    boolean mapsHaveEqualValues = values1.equals(values2);
    

    If values cannot contain duplicate values then you can either do the above without the sort using sets.

提交回复
热议问题