为了账号安全,请及时绑定邮箱和手机立即绑定

使用流从地图中求和值并收集到列表

使用流从地图中求和值并收集到列表

呼啦一阵风 2023-03-17 14:05:37
如果我有一个列表列表:List<List<Map<String, Object>>> myList = new ArrayList<>();List<Map<String, Object>> e1 = new ArrayList<>();e1.add(new HashMap<String, Object>(){{put("test", 1);}});e1.add(new HashMap<String, Object>(){{put("test", 6);}});List<Map<String, Object>> e2 = new ArrayList<>();e2.add(new HashMap<String, Object>(){{put("test", 9);}});e2.add(new HashMap<String, Object>(){{put("test", 2);}});myList.add(e1);myList.add(e2);我希望能够对myList内部列表 (e1和e2) 中的整数求和并返回总和列表:List<Integer> result = [7, 11]
查看完整描述

2 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

你可以这样做:


List<Integer> result = myList.stream()

        .map(list -> list.stream()

                        .flatMapToInt(map -> map.values()

                                                .stream()

                                                .mapToInt(i -> (int) i))

                        .sum())

        .collect(Collectors.toList());


查看完整回答
反对 回复 2023-03-17
?
三国纷争

TA贡献1804条经验 获得超7个赞

这是另一种更全球化的替代方法ernest_k解决方案更好更优雅,但这可能会帮助您了解更多关于流的信息


    BinaryOperator<Object> accumulator = (a, b) -> Double.parseDouble("" + a) + Double.parseDouble("" + b);


    List sums = myList.stream().map((e) -> e.stream()

            .map((content) -> content.values().stream().reduce(0, accumulator)).reduce(0, accumulator))

            .collect(Collectors.toList());

    System.out.println("sums \n"+sums);


查看完整回答
反对 回复 2023-03-17
  • 2 回答
  • 0 关注
  • 75 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信