作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有List<Transaction>
哪里Transaction
有amount
如BigDecimal
。
我想将所有 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/
我是一名优秀的程序员,十分优秀!