如何比较2 LinkedHashMap并获得键和差异;值?

时间:2018-05-22 07:46:37

标签: java collections hashmap linkedhashmap

有2个LinkedHashMaps。我必须检查两个LinkedHashMaps是否都有相同的密钥和&值。如果一个LinkedHashMap包含额外的键+值,那么它应该被打印或存储在3rd LinkedHashMap中。如果第二个LinkedHashMap中的任何键或值不同,则应通知它(在控制台中打印)

例如

Map1包含{A-a,B-b,C-c}

Map2包含{A-a,B-r,C-c,Z-z}

所以这里第3个LinkedHashMap应该包含{Z-z},因为它包含额外的键和

{B-r}应该在修改时打印

1 个答案:

答案 0 :(得分:1)

你可以使用这个类:)

public class MapCompare {
    private LinkedHashMap<String, String> differencesMap;
    private LinkedHashMap<String, String> extraMap;

    private void main(LinkedHashMap<String, String> map1, LinkedHashMap<String, String> map2) {
        this.differencesMap = new LinkedHashMap<>();
        this.extraMap = new LinkedHashMap<>();

        Set<Map.Entry<String, String>> set1 = ((LinkedHashMap<String, String>) map1.clone()).entrySet();
        Set<Map.Entry<String, String>> set2 = ((LinkedHashMap<String, String>) map2.clone()).entrySet();

        set1.removeAll(set2);
        compare(set1, map2);

        set1 = map1.entrySet();

        set2.removeAll(set1);
        compare(set2, map1);
    }

    private LinkedHashMap<String, String> getDifferencesMap() {
        return differencesMap;
    }

    private LinkedHashMap<String, String> getExtraMap() {
        return extraMap;
    }

    private void compare(Set<Map.Entry<String, String>> set, LinkedHashMap<String, String> map) {
        for (Map.Entry<String, String> entry : set) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (map.containsKey(key) || map.containsValue(value)) {
                differencesMap.put(key, value);
            } else {
                extraMap.put(key, value);
            }
        }
    }

    public static void main(String[] args) {
        LinkedHashMap<String, String> map1 = new LinkedHashMap<>();
        map1.put("A", "a");
        map1.put("B", "b");
        map1.put("C", "c");
        LinkedHashMap<String, String> map2 = new LinkedHashMap<>();
        map2.put("A", "a");
        map2.put("C", "c");
        map2.put("B", "r");
        map2.put("Z", "z");

        MapCompare mapCompare = new MapCompare();
        mapCompare.main(map1,map2);

        System.out.println("diff: " + mapCompare.getDifferencesMap());
        System.out.println("extra: " + mapCompare.getExtraMap());
    }
}