原创转载请注明出处:http://agilestyle.iteye.com/blog/2425206
reduce sum
private static void reduceSumTest1() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
Integer reduce = stream.reduce(0, (i, j) -> i + j);
System.out.println(reduce);
}
private static void reduceSumTest2() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
Integer reduce = stream.reduce(0, Integer::sum);
System.out.println(reduce);
}
private static void reduceSumTest3() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
stream.reduce(Integer::sum).ifPresent(System.out::println);
}
Console Output
28 28 28
Using reduce to sum the numbers in a stream
reduce max
private static void reduceMaxTest() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
stream.reduce(Integer::max).ifPresent(System.out::println);
}
Console Output
7
A reduce operation—calculating the maximum
reduce min
private static void reduceMinTest() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
stream.reduce(Integer::min).ifPresent(System.out::println);
}
Console Output
1
reduce even number multiply
private static void reduceTest() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
Integer result = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);
Optional.of(result).ifPresent(System.out::println);
}
Console Output
48
Reference
Manning.Java.8.in.Action.Lambdas.Streams.and.functional-style.programmin