dxh*_*707 5 java lambda functional-programming java-8 java-stream
假设我有这个课程:
public class Thing {
private BigDecimal field1;
private BigDecimal field2;
private BigDecimal otherField1;
private BigDecimal otherField2;
private BigDecimal otherField3;
}
Run Code Online (Sandbox Code Playgroud)
并且在另一个类I for--over a 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);
}
Run Code Online (Sandbox Code Playgroud)
我怀疑答案是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;
}
Run Code Online (Sandbox Code Playgroud)
或者,为了更精确一点,我将如何处理基于流的方法中的条件检查?我试图解决filter()问题而没有成功.
使用collect(),使用自定义收藏家帮手,没有什么不同IntSummaryStatistics.
things.stream()
.collect(ThingCollectorHelper::new,
ThingCollectorHelper::accept,
ThingCollectorHelper::combine);
Run Code Online (Sandbox Code Playgroud)
你的助手类将是这样的:
class ThingCollectorHelper {
BigDecimal sum1 = BigDecimal.ZERO;
BigDecimal sum2 = BigDecimal.ZERO;
void accept(Thing t) {
if (t.field1 != null)
sum1 = sum1.plus(t.field1);
if (t.field2 != null)
sum2 = sum2.plus(t.field2);
}
void combine(ThingCollectorHelper other) {
sum1 = sum1.plus(other.sum1);
sum2 = sum2.plus(other.sum2);
}
Run Code Online (Sandbox Code Playgroud)
}
由于您要统一处理这些字段,您可以考虑flatMap:
public BigDecimal addFields(List<Thing> things) {
return things.parallelStream()
.flatMap(thing -> Stream.of(thing.getField1(), thing.getField2()))
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public BigDecimal addOtherFields(List<Thing> things) {
return things.parallelStream()
.flatMap(thing ->
Stream.of(thing.getOtherField2(), thing.getOtherField3())
.filter(Objects::nonNull)
.map(thing.getOtherField1()::subtract)
).reduce(BigDecimal.ZERO, BigDecimal::add);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2761 次 |
| 最近记录: |