Java 8 stream reduces arbitrary class types
•
Java
Well, it's not a homework question, it's a question of "I got the Java 8 program and hope to finally pass the certification exam"
I tried to find the reduce () method in reducing the list of any class of a single member of my code (not the string or integer of most of the sample code I saw)
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
);
}
}
Solution
What works:
MyClass finalClass = myList.stream()
.reduce((a,b) -> new MyClass(a.accumulator + b.accumulator))
.orElse(new MyClass(0));
This requires two inputs, which must be enclosed in parentheses and reduced to one output Note that this returns an optional
A simple way to deal with this problem is to use orelse, which is equivalent to:
if(myList.size() == 0){
return new MyClass(0);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
