Java Reference
In-Depth Information
Stream Operations
A stream supports two types of operations:
Intermediate operations
Terminal operations
Intermediate operations are also known as lazy operations. Terminal operations are also known as eager
operations. Operations are known as lazy and eager based on the way they pull the data elements from the data
source. A lazy operation on a stream does not process the elements of the stream until another eager operation is
called on the stream.
Streams connect though a chain of operations forming a stream pipeline. A stream is inherently lazy until you
call a terminal operation on it. An intermediate operation on a stream produces another stream. When you call a
terminal operation on a stream, the elements are pulled from the data source and pass through the stream pipeline.
Each intermediate operation takes elements from an input stream and transforms the elements to produce an output
stream. The terminal operation takes inputs from a stream and produces the result.
Figure 3-1 shows a stream pipeline with a data source, three streams, and three operations. The filter and map
operations are intermediate operations and the reduce operation is a terminal operation.
Data
source
filter
map
reduce
Terminal operation
Intermediate operations
Figure 13-1. A stream pipeline
In the figure, the first stream (on the left) pulls data from the data source and becomes the input source for the
filter operation. The filter operation produces another stream containing data for which the filter condition is true.
The stream produced by the filter operation becomes the input for the map operation. The map operation produces
another stream that contains the mapped data. The stream produced by the map operation becomes the input for
the reduce operation. The reduce operation is a terminal operation. It computes and returns the result, and then the
processing of stream is over.
I have used the phrase “a stream pulls/consumes elements from its data source” in the preceding discussion.
this does not mean that the stream removes the elements from the data source; it only reads them. Streams are
designed to support functional programming in which data elements are read and operations on the read data elements
produce new data elements. however, the data elements are not modified (or at least should not be modified).
Tip
Stream processing does not start until a terminal operation is called. If you just call intermediate operations
on a stream, nothing exciting happens, except that they create another stream objects in memory, without reading
data from the data source. This implies that you must use a terminal operation on a stream for it to process the
data to produce a result. This is also the reason that the terminal operation is called a result-bearing operation and
intermediate operations are also called non result-bearing operations.
 
 
Search WWH ::




Custom Search