判断两个Map集合是否相等

判断两个Map集合是否相等

/**
 * 判断两个Map是否相等
 * @param map map1
 * @param map2 Map2
 * @return true:相等
 */
public static Boolean mapCompare(Map<String,Object> map,Map<String,Object> map2){
    try {
        if (MapUtils.isEmpty(map) && MapUtils.isEmpty(map2)){
            return true;
        }
        boolean mapIsNull = MapUtils.isEmpty(map) && MapUtils.isNotEmpty(map2);
        boolean mapIsNotNull = MapUtils.isNotEmpty(map) && MapUtils.isEmpty(map2);
        if (mapIsNull && mapIsNotNull){
            return false;
        }
        if (map.size() != map2.size()){
            return false;
        }

        AtomicReference<Boolean> flg = new AtomicReference<>(true);
        // TODO: 2022/1/11 更改时间是否要过滤掉
        map.forEach((k,v)->{
            // 判断key为空的情况
            if (k == null && !map2.containsKey(null)){
                flg.set(false);
            }
            if (v == null || map2.get(k) == null){
                boolean b = v == null && map2.get(k) != null;
                boolean b1 = v != null && map2.get(k) == null;
                if (b || b1){
                    flg.set(false);
                }
            }else if (!v.equals(map2.get(k))){
                flg.set(false);
            }
        });
        return flg.get();
    }catch (Exception e){
        e.printStackTrace();
        throw new RuntimeException("Map元素比对异常:",e.getCause());
    }
}

public static void main(String[] args) {
    Map<String,Object> map = new HashMap<>();
    Map<String,Object> map1 = new HashMap<>();

    map.put("a",2342);
    map.put("ab",2.342);
    map.put("ad","这是测试的数据");
    map.put("ac","asdf");
    map.put(null,"2342");
    map.put("aasd","kasdf_jsld#asdf");
    map.put(null,2342);
    map.put("asdfdg",2.342);

    map1.put("a",2342);
    map1.put("ab",2.342);
    map1.put("ac","asdf");
    map1.put("ad","这是测试的数据");
    map1.put("aasd","kasdf_jsld#asdf");
    map1.put(null,"2342");
    map1.put(null,2342);
    map1.put("asdfdg",2.342);

    System.out.println(mapCompare(map,map1)); // true
    System.out.println(mapCompare(map1,map)); // true
}

你可能感兴趣的:(其他,javaSE,java)