stream中reduce的三种用法,解决对象集合中的金额累加
这里记一个写自己系统的功能时遇到的一个问题:
系统设计为账目对象,我需要求出所有账目的总金额,打算使用统计方法
accountBooks.stream().mapToDouble((x) -> x.getAccountNum()).summaryStatistics();
但出现报错,原因是我的账目对象对于金额的字段类型为BigDecimal,而BigDecimal不能转换为Double类型进行计算,于是抛出一个问题:
如何才能用简洁的代码实现金额累加的功能
这里经过查阅我发现了另一种方式stream中reduce
这里使用reduce接收两个参数的方法
accountBooks.stream()
.map(AccountBook::getAccountNum)
.reduce(BigDecimal.ZERO, BigDecimal::add);
这里为初始值设为BigDecimal.ZERO,通过BigDecimal::add对AccountBook::getAccountNum进行累加,最终得到想要的累计金额
这里还涉及到parallel()并行模式的使用
reduce还有接收1个参数和3个参数的方法,这里引用一下:
一个参数:
public static void main(String[] args) {
Optional<Integer> opt = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer acc, Integer n) {
return acc + n;
}
});
//Optional<Integer> opt = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9).reduce((acc, n) -> acc + n);
if (opt.isPresent()) {
System.out.println("累加和为:" + opt.get());
}
}
三个参数:
public static void main(String[] args) {
int sum = Stream.of(1, 2, 3, 4)
.reduce(0, (n1, n2) -> {
int ret = n1 + n2;
System.out.println(n1 + "(n1) + " + n2 + "(n2) = " + ret);
return ret;
}, (s1, s2) -> {
int ret = s1 + s2;
System.out.println(s1 + "(s1) + " + s2 + "(s2) = " + ret);
return ret;
});
System.out.println("sum:" + sum);
}
详情可参照原文