Skip to content

Instantly share code, notes, and snippets.

@yusuke2255
Created August 5, 2015 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yusuke2255/2727e6c569364a3ae1a7 to your computer and use it in GitHub Desktop.
Save yusuke2255/2727e6c569364a3ae1a7 to your computer and use it in GitHub Desktop.
[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