如何通过键和值比较两个图并将差异图存储在结果图中 [英] How to compare two maps by both key and value and storing difference map in resultant map

查看:60
本文介绍了如何通过键和值比较两个图并将差异图存储在结果图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有两张地图:

Lets say I have two maps:

Map mapA = new HashMap();
Map mapB = new HashMap();

mapA.put("JEETENDRA", "24");
mapA.put("AHUJA", "24"); --1A
mapA.put("AHUJA", "25");---2A
mapA.put("PAL", "24");

mapB.put("AHUJA", "24");
mapB.put("JEETENDRA", "24");---1B
mapB.put("PAL", "24");

现在我想通过键和值来比较两个映射,因为2A和1A具有通用的键.理想情况下,我知道它是错误的,因为键对于map应该是唯一的,但是在代码中,我正在检索两列记录并将其存储为map.

Now i want to compare both maps by both key and value since 2A and 1A have key common. I know ideally its wrong since key should be unique for map but in code I am retrieving two column record and storing it as map.

MapA在操作之前.
MapB经过一些操作.

MapA is before operations.
MapB is after some operations.

推荐答案

您可以使用此方法,在这里我使用了泛型,并且使用了一个TreeMap及其名称结果来保存此方法中两个HashMaps中的所有键.您将在Hashmaps中获得所有匹配的对象

you can use this method, here I have used the Generics, and I have used one TreeMap with name result to hold all keys inside both HashMaps , from this method you will get all the matched objects in Hashmaps

public static <K extends Comparable<? super K>, V>
    Map<K, Boolean> compareKeysAndValues(final Map<K, V> map1,
        final Map<K, V> map2){
        final Collection<K> allKeys = new HashSet<K>();
        allKeys.addAll(map1.keySet());
        allKeys.addAll(map2.keySet());
        final Map<K, Boolean> result = new TreeMap<K, Boolean>();
        for(final K key : allKeys){
            result.put(key,
                map1.containsKey(key) == map2.containsKey(key) &&
                Boolean.valueOf(equal(map1.get(key), map2.get(key))));
        }
        return result;
    }

如果要获取不同的值,只需将result.put函数中的check反转即可.

and if you want to get the value which are different simply reverse the check in result.put function

这篇关于如何通过键和值比较两个图并将差异图存储在结果图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆