Created
August 5, 2015 04:02
-
-
Save yusuke2255/2727e6c569364a3ae1a7 to your computer and use it in GitHub Desktop.
[Java8] Stream reduce sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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