Java Reference
In-Depth Information
You have seen the following code that uses a pipeline of stream operations to compute the sum of odd integers
from 1 to 5:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 1)
.map(n -> n * n)
.reduce(0, Integer::sum);
Figure 3-2 through Figure 3-5 show the states of the stream pipeline as operations are added. Notice that no data
flows through the stream until the reduce operation is called. The last figure shows the integers in the input stream for
an operation and the mapped (or transformed) integers produced by the operation. The reduce terminal operation
produces the result 35.
1, 2,
3, 4,
5
numbers.stream( )
Figure 13-2. The stream pipeline after the stream object is created
1, 2,
3, 4,
5
filter
numbers.stream( ).filter(n -> n % 2 == 1)
Figure 13-3. The stream pipeline after the filter operation is called
1, 2,
3, 4,
5
filter
map
numbers.stream( ).filter(n -> n % 2 == 1). map(n -> n * n)
Figure 13-4. The stream pipeline after the map operation is called
1, 2,
3, 4,
5
5, 4, 3, 2, 1
filter
5, 3, 1
map
25, 9, 1
reduce
35
numbers.stream( ).filter(n -> n % 2 == 1).map(n -> n * n).reduce(0, Integer::sum)
Figure 13-5. The stream pipeline after the reduce operation is called
Ordered Streams
A stream can be ordered or unordered. An ordered stream preserves the order of its elements. The Streams API lets
you convert an ordered stream into an unordered stream. A stream can be ordered because it represents an ordered
data source such as a list or a sorted set. You can also convert an unordered stream into an ordered stream by applying
an intermediate operation such as sorting.
 
 
Search WWH ::




Custom Search