map key相同 合并 value


 class CombineVale {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Map> list = new ArrayList<>();
        Map map0 = new HashMap();
        map0.put(1, 1);
        list.add(map0);
        Map map1 = new HashMap();
        map1.put(3, 4);
        list.add(map1);
        Map map2 = new HashMap();
        map2.put(1, 2);
        list.add(map2);
        Map map3 = new HashMap();
        map3.put(1, 3);
        list.add(map3);
        Map map4 = new HashMap();
        map4.put(2, 2);
        list.add(map4);
        Map map5 = new HashMap();
        map5.put(2, 1);
        list.add(map5);
        Map map6 = new HashMap();
        map6.put(3, 1);
        list.add(map6);

        // 要求将上面的List<Map>中的map中key相同的value合并
        // 最终得到下面的结果List<Map<Object,List>>,其中三个map分别为
        // 1->[1,2,3]
        // 2->[2,1]
        // 3->[4,3]

        Map m = mapCombine(list);
        System.out.println(m);

    }

    public static Map mapCombine(List<Map> list) {
        Map<Object, List> map = new HashMap<>();
        for (Map m : list) {
            Iterator<Object> it = m.keySet().iterator();
            while (it.hasNext()) {
                Object key = it.next();
                if (!map.containsKey(key)) {
                    List newList = new ArrayList<>();
                    newList.add(m.get(key));
                    map.put(key, newList);
                } else {
                    map.get(key).add(m.get(key));
                }
            }
        }
        return map;
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值