gpt4 book ai didi

java - 将流 sum() 方法应用于列表的 N 个不同字段,在一次迭代中给出 N 个总和结果

转载 作者:行者123 更新时间:2023-12-01 19:33:27 25 4
gpt4 key购买 nike

class A
{
Integer a;
Integer b;
Integer c;
}

List<A> inputList= func();
X x=new X();
int sumA = inputList.stream().mapToInt(e->e.getA()).sum();
int sumB = inputList.stream().mapToInt(e->e.getB()).sum();
int sumC = inputList.stream().mapToInt(e->e.getC()).sum();

x.setSumA(sumA);
x.setSumB(sumB);
x.setSumC(sumC);

这将解决这个问题,但会有三个迭代,我想在单次迭代中执行它,而不使用仅使用流的 for 循环。

最佳答案

您可以使用 reduce 在单个 Stream 管道中计算 3 个总和:

X sums = inputList.stream()
.reduce(new X(0,0,0),
(x,e) -> new X(x.getSumA()+e.getA(),
x.getSumB()+e.getB(),
x.getSumC()+e.getC()),
(x1,x2) -> new X(x1.getSumA()+x2.getSumA(),
x1.getSumB()+x2.getSumB(),
x1.getSumC()+x2.getSumC()));

关于java - 将流 sum() 方法应用于列表的 N 个不同字段,在一次迭代中给出 N 个总和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58706093/

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