Comparing two hashmaps for equal values and same key sets?

后端 未结 6 968
北荒
北荒 2020-12-03 02:18

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 oth

6条回答
  •  佛祖请我去吃肉
    2020-12-03 03:13

    if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==

    boolean b = map1.entrySet().stream().filter(value -> 
                map2.entrySet().stream().anyMatch(value1 -> 
                (value1.getKey().equals(value.getKey()) && 
      value1.getValue().equals(value.getValue())))).findAny().isPresent();   
    
    
    System.out.println("comparison  "+b);
    

提交回复
热议问题