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

有帮助的话对Micro极微完美女装品牌店淘宝店支持支持包         

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

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

public class DifferenceMap {
    public <K,V> MapDifference<K,V> difference(Map<? extends K,? extends V> left,Map<? extends K,? extends V> right){
        Map<K,V> difleft = new HashMap();//保存left有但right没有的数据
        Map<K,V> difright = new HashMap(right);//保存right有但left没有的数据
        Map<K,V> samemap = new HashMap();//保存俩共有的数据
        /*将left通过entrySet转为Map.entrySet类型的set集合,方便可以获取键值对*/
        Iterator iterator =  left.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<? extends K, ? extends V> 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<K, V>{
        final Map<K, V> difleft;
        final Map<K, V> difright;
        final Map<K, V> samemap;
        MapDifference(Map<K, V> difleft, Map<K, V> difright, Map<K, V> samemap){
            this.difleft = difleft;
            this.difright = difright;
            this.samemap = samemap;
        }

        public Map<K, V> getDifleft() {
            return difleft;
        }

        public Map<K, V> getDifright() {
            return difright;
        }

        public Map<K, V> getSamemap() {
            return samemap;
        }
    }

    public static void main(String[] args) {
        Map mapl = new HashMap<String,String>();
        mapl.put("1","1");
        mapl.put("2","2");
        mapl.put("3","3");
        Map mapr = new HashMap<String,String>();
        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());
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子鞋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值