减少 java 中自定义对象的操作
2022-09-02 23:32:42
如何使用 Reduce 操作对对象的两个字段执行求和。
例如:
class Pojo
{
public Pojo(int a, int b) {
super();
this.a = a;
this.b = b;
}
int a ;
int b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
Pojo object1 = new Pojo(1, 1);
Pojo object2 = new Pojo(2, 2);
Pojo object3 = new Pojo(3, 3);
Pojo object4 = new Pojo(4, 4);
List<Pojo> pojoList = new ArrayList<>();
pojoList.add(object1);
pojoList.add(object2);
pojoList.add(object3);
pojoList.add(object4);
我可以像这样执行求和:IntStream
int sum = pojoList.stream()
.mapToInt(ob -> (ob.getA() + ob.getB()))
.sum();
我想使用reduce执行相同的操作,但不知何故,我没有得到正确的语法:
pojoList.stream()
.reduce(0, (myObject1, myObject2) -> (myObject1.getA() + myObject2.getB()));