Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Java8] Stream reduce sample
import java.util.Arrays;
import java.util.Optional;
public class ReduceTest {
public static void main(String[] args) {
Optional<Sum> summary = Arrays.asList(new Sum(1, 10),new Sum(2, 15),new Sum(3, 5)).stream().reduce((sum1,sum2) -> {
if (Optional.ofNullable(sum1).isPresent() == false) {
System.out.println("Sum1 is empty.");
return sum2;
}
if (Optional.ofNullable(sum2).isPresent() == false) {
System.out.println("Sum2 is empty.");
return sum1;
}
return new Sum(sum1.getA() + sum2.getA(), sum1.getB() + sum2.getB());
});
System.out.println("[RESULT] a = " + summary.get().getA() + " , b = " + summary.get().getB());
}
static class Sum {
private final long a;
private final long b;
public Sum(long a, long b) {
super();
this.a = a;
this.b = b;
}
public long getA() {
return a;
}
public long getB() {
return b;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.