假设我有这个类:
public class Thing {
private BigDecimal field1;
private BigDecimal field2;
private BigDecimal otherField1;
private BigDecimal otherField2;
private BigDecimal otherField3;
}
在另一个类中,我使用 for-each 遍历 List<Thing> things
,将 field1 和 field2 添加到总和中,并在迭代完成后返回该总和。
但是我想使用 Java 流来完成这个任务。以下是我的代码 - 它可以工作,但我觉得肯定有一种方法可以将其压缩成一个流:
public BigDecimal addFields(List<Thing> things) {
BigDecimal field1sum = things.parallelStream()
.filter(thing -> thing.getField1() != null)
.map(Thing::getField1)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal field2sum = things.parallelStream()
.filter(thing -> thing.getField2() != null)
.map(Thing::getField2)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return field1sum.add(field2sum);
}
我猜测答案是使用
reduce()
方法,它需要三个参数,其中一个是 BiFunction,但我还没有找出如何使它工作。编辑:我认为我可以将 (x,y) -> x.add(y)
传递给 reduce()
,但问题变成了如何对这两个字段都进行 map()
?此外,是否可能将这段命令式代码转换为函数式流?
public BigDecimal addOtherFields(List<Thing> things) {
BigDecimal result = BigDecimal.ZERO;
for (Thing thing : things) {
if (thing.getOtherField2() != null) {
BigDecimal otherField2 = thing.getOtherField2();
otherField2 = thing.getOtherField1().subtract(otherField2);
result = result.add(otherField2);
} else if (thing.getOtherField3() != null) {
BigDecimal otherField3 = thing.getOtherField3();
otherField3 = thing.getOtherField1.subtract(otherField3);
result = result.add(otherField3);
}
}
return result;
}
或者更准确地说,我该如何在基于流的方法中处理条件检查?我试图用
filter()
进行过滤,但未成功。