java 使用 lambda 对 List 中的 BigDecimal 值求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38124086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:09:06 来源:igfitidea点击:
Sum BigDecimal values in List with lambda
提问by Hyman Daniel
I have a simple class:
我有一个简单的类:
class Simple {
private String count;
private BigDecimal amount;
private String label;
}
and have a List: List<Simple> simples = new ArrayList<>();
how I can sum all amounts of all simples in list with Lambda in Java 8?
并有一个列表:List<Simple> simples = new ArrayList<>();
如何在 Java 8 中使用 Lambda 对列表中的所有简单数求和?
回答by Arnaud Denoyelle
It is quite easy with a Stream and a reducer :
使用 Stream 和 reducer 很容易:
BigDecimal sum = simples
.stream()
.map(Simple::getAmount)
.reduce(BigDecimal::add)
.get();
回答by Jean Logeart
Try:
尝试:
BigInteger sum = simples.stream()
.map(Simple::getAmount)
.reduce(BigInteger.ZERO, BigInteger::add);