我有3个类,A类,B类,C类。A类包含B类列表,B类包含C类列表。C类包含基元。
class A {
List<B> bList;
//getter
}
class B {
List<C> cList;
//getter
}
class C {
int a;
int b;
int c;
//getter
}
我想做以下几件事。
A aInstance = new A();
List<B>bs = aInstance.getBList();
for(B b: bs) {
List<C> cs = b.getCList();
for(C c: cs) {
sum_a += c.a;
sum_b_c += c.b + c.c;
}
}
我如何用java8特定的流来实现这一点?
发布于 2018-05-28 18:27:57
例如,您可以使用两个元素将其reduce
到一个整数数组中:
int[] result = aInstance
.getBList()
.stream()
.flatMap(b -> b.getcList().stream())
.map(c -> new int[] { c.a, c.b + c.c })
.reduce((left, right) -> {
int[] newV = new int[2];
newV[0] = left[0] + right[0];
newV[1] = left[1] + right[1];
return newV;
})
.orElse(new int[] { 0, 0 });
或者更好的方式是通过collect
(不用创建很多int []
对象):
int[] result = aInstance
.getBList()
.stream()
.flatMap(b -> b.getCList().stream())
.collect(
() -> new int[2],
(arr, c) -> {
arr[0] += c.a;
arr[1] += c.b + c.c;
},
(left, right) -> {
left[0] += left[0];
right[1] += right[1];
});
发布于 2018-05-28 18:28:01
在collect
步骤中应该有一个flatMap
步骤和一个适当的累加器,如下所示:
int[] sums = a.bList.stream().flatMap(b -> b.cList.stream())
.collect(() -> new int[2], (acc, v) -> {
acc[0] += v.a;
acc[1] += v.b + v.c;
}, (acc, other) -> {
acc[0] += other[0];
acc[1] += other[1];
});
发布于 2018-05-28 18:27:33
您需要一些类型来保存这两个和,例如:
public class Sums {
int sumA;
int sumBC;
public Sums (int sumA, int sumBC) {this.sumA=sumA; this.sumBC=sumBC;}
public int getA() {return sumA;}
public int getBC() {return sumBC;}
}
现在,您为要求和的元素创建一个Stream
,并将其缩减为一个Sums
实例:
Sums sums = aInstance.getBList()
.stream()
.flatMap(b->b.getCList().stream())
.reduce(new Sums(0,0),
(s,c)->new Sums(s.getA()+c.getA(),s.getBC()+c.getB()+c.getC()),
(s1,s2)->new Sums(s1.getA()+s2.getA(),s1.getBC()+s2.getBC()));
https://stackoverflow.com/questions/50564044
复制相似问题