How to receive difference of maps in java?

前端 未结 7 928
不知归路
不知归路 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 09:54

    Building on Vlad's example to work with maps of different sizes

    public static <K, V> Map<K, V> mapDiff(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
            Map<K, V> difference = new HashMap<>();
            difference.putAll(left);
            difference.putAll(right);
    
            difference.entrySet().removeAll(left.size() <= right.size() ? left.entrySet() : right.entrySet());
    
            return difference;
        }
    
    0 讨论(0)
  • 2021-02-05 09:57

    Try using guava's MapDifference.

    0 讨论(0)
  • 2021-02-05 10:01

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

        Map<String, Object> map1 = new HashMap<String, Object>() {{
            put("A", "1");
            put("B", "2");
            put("C", "3");
        }};
        Map<String, Object> map2 = new HashMap<String, Object>() {{
            put("A", "1");
            put("B", "2");
            put("D", "3");
        }};
        Map<String, Object> newList = map1.keySet().stream().filter(str -> !map2.containsKey(str)).collect(Collectors.toMap(v -> v, v -> map1.get(v)));
        Map<String, Object> 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);
    
    0 讨论(0)
  •     Set<Entry<String, Object>> diff = new HashSet<Entry<String, Object>>((map1.entrySet()));
        diff.addAll(map2.entrySet());//Union
        Set<Entry<String, Object>> tmp = new HashSet<Entry<String, Object>>((map1.entrySet()));
        tmp.retainAll(map2.entrySet());//Intersection
        diff.removeAll(tmp);//Diff
    
    0 讨论(0)
  • 2021-02-05 10:09

    How about google guava?:

    Maps.difference(map1,map2)
    
    0 讨论(0)
  • 2021-02-05 10:09

    Here is a simple snippet you can use instead of massive Guava library:

    public static <K, V> Map<K, V> mapDifference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
        Map<K, V> difference = new HashMap<>();
        difference.putAll(left);
        difference.putAll(right);
        difference.entrySet().removeAll(right.entrySet());
        return difference;
    }
    

    Check out the whole working example

    0 讨论(0)
提交回复
热议问题