Java集合 两个Map-value值求和

Java集合 两个Map-value值求和

应用场景
两个map<k,v>中k值相同的value值求和返回map计算

代码案例

    /**
     * Map外层遍历
     */
    public Map<Integer, Map<Integer, Integer>> mapCount(Map<Integer, Map<Integer, Integer>> quoraListMapSource, Map<Integer, Map<Integer, Integer>> quoraListMapTarget) {
        for (Integer sourceKey : quoraListMapSource.keySet()) {
            if (quoraListMapTarget.containsKey(sourceKey)) {
                Map<Integer, Integer> integerMap = mapValueCount(quoraListMapSource.get(sourceKey), quoraListMapTarget.get(sourceKey));
                quoraListMapTarget.put(sourceKey, integerMap);
            }
        }
        return quoraListMapTarget;
    }

    /**
     * MapValue统计
     */
    public Map<Integer, Integer> mapValueCount(Map<Integer, Integer> quoraListMapSource, Map<Integer, Integer> quoraListMapTarget) {
        for (Integer sourceKey : quoraListMapSource.keySet()) {
            if (quoraListMapTarget.containsKey(sourceKey)) {
                quoraListMapTarget.put(sourceKey, quoraListMapSource.get(sourceKey) + quoraListMapTarget.get(sourceKey));
            }
        }
        return quoraListMapTarget;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java 8的Stream API来合并两个List<Map<String, Integer>>集合。 假设有以下两个List<Map<String, Integer>>集合: ```java List<Map<String, Integer>> list1 = new ArrayList<>(); Map<String, Integer> map1 = new HashMap<>(); map1.put("a", 1); map1.put("b", 2); list1.add(map1); List<Map<String, Integer>> list2 = new ArrayList<>(); Map<String, Integer> map2 = new HashMap<>(); map2.put("b", 3); map2.put("c", 4); list2.add(map2); ``` 可以使用以下代码将这两个集合合并: ```java List<Map<String, Integer>> mergedList = Stream.concat(list1.stream(), list2.stream()) .flatMap(map -> map.entrySet().stream()) .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.summingInt(Map.Entry::getValue))) .entrySet().stream() .map(entry -> { Map<String, Integer> map = new HashMap<>(); map.put(entry.getKey(), entry.getValue()); return map; }) .collect(Collectors.toList()); ``` 这段代码的流程如下: - 使用Stream.concat()方法将两个集合合并为一个Stream对象。 - 使用flatMap()方法将每个Map对象的entry集合转换为一个新的Stream对象。 - 使用Collectors.groupingBy()方法将entry集合按照key分组,并将value求和。 - 使用entrySet()方法将Map对象转换为一个entry集合。 - 使用map()方法将每个entry转换为一个新的Map对象。 - 使用Collectors.toList()方法将所有的Map对象收集到一个List集合中。 最终的mergedList集合中的元素为: ```java [{a=1}, {b=5}, {c=4}] ``` 其中,{a=1}表示key为"a",value为1;{b=5}表示key为"b",value为5;{c=4}表示key为"c",value为4。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值