gpt4 book ai didi

java - 集合.forEach : How to add up values?

转载 作者:行者123 更新时间:2023-12-01 18:22:41 38 4
gpt4 key购买 nike

我有List<Transaction>哪里TransactionamountBigDecimal

我想将所有 amount 加起来在此列表中。我做了一些事情

BigDecimal spent = new BigDecimal("0.0");
transactions.forEach(t -> spent.add(t.getAmount()));
System.out.println(spent);

当我运行这个时,spent结果是0.0

此外,从语法上看 transactions.forEach(t -> spent = spent.add(t.getAmount()));抛出编译错误。

我正在尝试学习在不使用 for each 的情况下做到这一点循环

想法?

最佳答案

阅读 Adding up BigDecimals using Streams 后,我发现以下是我需要的

final Function<Transaction, BigDecimal> transactionAmountMapper = Transaction::getAmount;
final BigDecimal result = entry.getValue().stream().map(transactionAmountMapper).reduce(BigDecimal.ZERO, BigDecimal::add);

关于java - 集合.forEach : How to add up values?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27208782/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com