gpt4 book ai didi

java - 在 Java 流中添加多个字段(和条件流操作)

转载 作者:搜寻专家 更新时间:2023-11-01 01:32:30 24 4
gpt4 key购买 nike

假设我有这个类(class):

public class Thing {
private BigDecimal field1;
private BigDecimal field2;

private BigDecimal otherField1;
private BigDecimal otherField2;
private BigDecimal otherField3;
}

在另一个类中,我为每个 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()事情没有成功。

最佳答案

collect() 与自定义收集器助手一起使用,与 IntSummaryStatistics 不同。

things.stream()
.collect(ThingCollectorHelper::new,
ThingCollectorHelper::accept,
ThingCollectorHelper::combine);

你的助手类将是这样的:

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);
}

关于java - 在 Java 流中添加多个字段(和条件流操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com