减少java中自定义对象的操作

Nir*_*ane 8 java java-8 java-stream

如何使用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);
Run Code Online (Sandbox Code Playgroud)

我可以IntStream这样使用:

int sum = pojoList.stream()
                  .mapToInt(ob -> (ob.getA() + ob.getB()))
                  .sum();
Run Code Online (Sandbox Code Playgroud)

我想使用reduce执行相同的操作,但不知怎的,我没有得到正确的语法:

pojoList.stream()
        .reduce(0, (myObject1, myObject2) -> (myObject1.getA() + myObject2.getB()));
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 14

好吧,如果你想调用reduce IntStream:

int sum = pojoList.stream()
                  .mapToInt(ob ->(ob.getA()+ob.getB()))
                  .reduce(0, (a,b)->a+b);
Run Code Online (Sandbox Code Playgroud)

当然,同样适用于Stream<Integer>:

int sum = pojoList.stream()
                  .map(ob ->(ob.getA()+ob.getB()))
                  .reduce(0, (a,b)->a+b);
Run Code Online (Sandbox Code Playgroud)

或者使用方法参考:

int sum = pojoList.stream()
                  .map(ob ->(ob.getA()+ob.getB()))
                  .reduce(0, Integer::sum);
Run Code Online (Sandbox Code Playgroud)

或没有map():

int sum = pojoList.stream()
                  .reduce(0, (s,ob)->s+ob.getA()+ob.getB(),Integer::sum);
Run Code Online (Sandbox Code Playgroud)

在最后一个例子中,我使用了变体:

<U> U reduce(U identity,
             BiFunction<U, ? super T, U> accumulator,
             BinaryOperator<U> combiner);
Run Code Online (Sandbox Code Playgroud)

因为减小的值(a Integer)不同于Stream元素的类型.

第一个参数是标识值 - 0.

第二个参数将当前元素的getA()getB()值添加Pojo到中间和.

第三个参数组合了两个部分和.

  • 你应该解释一下,错误是reduce函数必须采用与输出相同的参数. (3认同)

Ole*_*hov 6

sum() 方法实现如下:

public final int sum() {
    return reduce(0, Integer::sum);
}
Run Code Online (Sandbox Code Playgroud)

替换sum()reduce()

int sum = pojoList.stream()
                  .mapToInt(ob -> (ob.getA() + ob.getB()))
                  .reduce(0, Integer::sum);
Run Code Online (Sandbox Code Playgroud)

或者,没有mapToInt()

int pojoSum = pojoList.stream()
                      .reduce(0, (sum, ob) -> sum + ob.getA() + ob.getB(), Integer::sum);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅归约运算段落。