亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用流從地圖中求和值并收集到列表

使用流從地圖中求和值并收集到列表

呼啦一陣風 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 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號