俩map求差值和相同数据的集合

          好轮子谷歌造,以下代码是模仿轮子帝国谷歌maps而诞生的另个一粗糙的轮子。当然这个方法是即兴而来的,并不如谷歌的maps好。

         我们对源码进行了简化,只获取俩map的左差值、右差值和相同数据,并用返回静态内部类的方式返回多个集合。

public class DifferenceMap {
    public  MapDifference difference(Map left,Map right){
        Map difleft = new HashMap();//保存left有但right没有的数据
        Map difright = new HashMap(right);//保存right有但left没有的数据
        Map samemap = new HashMap();//保存俩共有的数据
        /*将left通过entrySet转为Map.entrySet类型的set集合,方便可以获取键值对*/
        Iterator iterator =  left.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            K leftKey = entry.getKey();
            V leftValue = entry.getValue();
            /*移除key和value都不相同的数据,如果只移除key不相同的去掉right.containsValue(leftValue)即可*/
            if (right.containsKey(leftKey)&&right.containsValue(leftValue)){
                difright.remove(leftKey);
                samemap.put(leftKey,leftValue);
            }else{
                difleft.put(leftKey,leftValue);
            }
        }
        return new MapDifference<>(difleft,difright,samemap);
    }
    private static class MapDifference{
        final Map difleft;
        final Map difright;
        final Map samemap;
        MapDifference(Map difleft, Map difright, Map samemap){
            this.difleft = difleft;
            this.difright = difright;
            this.samemap = samemap;
        }

        public Map getDifleft() {
            return difleft;
        }

        public Map getDifright() {
            return difright;
        }

        public Map getSamemap() {
            return samemap;
        }
    }

    public static void main(String[] args) {
        Map mapl = new HashMap();
        mapl.put("1","1");
        mapl.put("2","2");
        mapl.put("3","3");
        Map mapr = new HashMap();
        mapr.put("3","3");
        mapr.put("4","4");
        mapr.put("5","5");
        DifferenceMap differenceMap = new DifferenceMap();
        MapDifference mapDifference = differenceMap.difference(mapl,mapr);
        System.out.println(mapDifference.getDifleft().toString());
        System.out.println(mapDifference.getDifright().toString());
        System.out.println(mapDifference.getSamemap().toString());
    }
}

 

你可能感兴趣的:(俩map求差值和相同数据的集合)