Jason Jason - 25 days ago 16
Java Question

Java 8 Stream Reduce of Arbitrary Class Type

Okay, this is NOT a homework question, this is a "me getting with the Java 8 program and hoping to eventually pass the certification exam" question.

I'm trying to figure out the reduce() method, in terms of reducing a List of an arbitary class (not the String or Integer most example code I see uses) to a single member of my code.

package playground;

import java.util.Arrays;
import java.util.List;

public class TestClass {

public static class MyClass {

private int accumulator = 0;

public MyClass() {

}

public MyClass(int initValue) {
this.accumulator = initValue;
}

public int getAccumulator() {
return accumulator;
}

public void setAccumulator(int accumulator) {
this.accumulator = accumulator;
}


}

public static void main(String... args) {

MyClass mc1 = new MyClass(6);
MyClass mc2 = new MyClass(8);
MyClass mc3 = new MyClass(3);

List<MyClass> myList = Arrays.asList(mc1, mc2, mc3);
MyClass finalClass = myList.stream().reduce(new MyClass(0),
// need the correct lambda function here
);


}


}

Answer

Something to the effect of:

MyClass finalClass = myList.stream()
    .reduce((a, b) -> new MyClass(a.accumulator + b.accumulator))
    .orElse(new MyClass(0));

This takes 2 inputs, which have to be surrounded by parentheses, and reduces them to one output. Note this returns an Optional.

An easy way to handle this is with orElse which is equivalent to:

if(myList.size() == 0){
    return new MyClass();
}
Comments