How to receive difference of maps in java?

前端 未结 7 957
不知归路
不知归路 2021-02-05 09:36

I have two maps:

Map map1;
Map map2;

I need to receive difference between these maps. Does exist ma

7条回答
  •  时光取名叫无心
    2021-02-05 10:01

    Simple way to do it. if you want complex way, you can change filter to compare value.

        Map map1 = new HashMap() {{
            put("A", "1");
            put("B", "2");
            put("C", "3");
        }};
        Map map2 = new HashMap() {{
            put("A", "1");
            put("B", "2");
            put("D", "3");
        }};
        Map newList = map1.keySet().stream().filter(str -> !map2.containsKey(str)).collect(Collectors.toMap(v -> v, v -> map1.get(v)));
        Map oldList = map2.keySet().stream().filter(str -> !map1.containsKey(str)).collect(Collectors.toMap(v -> v, v -> map2.get(v)));
    
        System.out.println(newList);
        System.out.println(oldList);
    

提交回复
热议问题