Java Reference
In-Depth Information
element from the stream. This process continues until all elements of the stream have been passed to the accumulator.
The returned value from the last call of the accumulator is returned from the reduce() method. The following snippet of
code performs the summation of all integers in the stream:
// Sum all integers in the stream
int sum = squaredNumbersStream.reduce(0, (n1, n2) -> n1 + n2);
The Integer class contains a static sum() method to perform sum of two integers. You can rewrite the code using
a method reference, like so:
// Sum all integers in the stream
int sum = squaredNumbersStream.reduce(0, Integer::sum );
In this example, I have broken down each operation on the stream in a single statement. Note that you cannot
use the returned streams from intermediate operations, except to apply other operations on them. Typically, you
care about the result of the terminal operation, not the intermediate streams. Streams have been designed to support
method chaining to avoid temporary variables, which you used in this example. You can combine these statements
into one statement as follows:
// Sum all integers in the numbers list
int sum = numbers.stream()
.filter(n -> n %2 ==1)
.map(n -> n * n)
.reduce(0, Integer::sum);
I will chain all method calls on streams to form only one statement in subsequent examples. Listing 13-1 contains
the complete program for this example. Note that you are working with only integers in this example. For better
performance, you could have used an IntStream in this example. I will show you how to use an IntStream later.
Listing 13-1. Computing the Sum of the Squares of All Odd Integers From 1 to 5
// SquaredIntsSum.java
package com.jdojo.streams;
import java.util.Arrays;
import java.util.List;
public class SquaredIntsSum {
public static void main(String[] args) {
// Get a list of integers from 1 to 5
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Compute the sum of the squares of all odd integers in the list
int sum = numbers.stream()
.filter(n -> n % 2 == 1)
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println("Sum = " + sum);
}
}
Sum = 35
 
Search WWH ::




Custom Search