242 total views, 2 views today
Welcome to Java 8 series and to my post ‘Java 8 Stream pipelines explained’. In this post, you will learn about Stream pipelines, source of a stream, intermediate operation and terminal operations.
Java 8 streams are classified into two operations. Intermediate operation and Terminal Operation.
Both are combined to form a Stream pipeline.
Stream pipeline = A Source + 0…N intermediate operation + A Terminal operation
Stream pipeline will start from a source. Sources can be an array, or a generator or I/O channel. A stream will be created from a source.
Stream pipeline can have zero to N number of intermediate operations such as filter, map, etc. The intermediate operation allows us to do apply some transformation to the source data. We can transform each element of the source by applying an intermediate operation.
Each intermediate operation will return a new stream. This means source data remains unchanged when an intermediate operation is performed. For example, when the filter() is applied to the source data, a new filtered output of stream will be created but the source data will not be modified or filtered.
Intermediate operations are always lazy loading. We can apply N number of intermediate operations but data will only be loaded when a terminal operation is invoked. This lazy loading helps to optimize performance. Data will only be loaded when it is needed.i.e when a terminal operation is applied. When you invoke an intermediate operation on a stream, the operation is not executed immediately but it does execute only when a terminal operation is invoked.
Every intermediate operation will create a new stream and it is lazy loaded.
Below are the list of intermediate operations
Stream pipeline will end with a single terminal operation such as foreach, count, collect, sum. A terminal operation produces the final output. Once the terminal operation is applied to the stream, we cannot reuse the stream again. We have to create a new stream and create a new stream pipeline again from the source. So, the stream cannot be reused when a terminal operation is applied or invoked. To put in a simpler way, Stream is considered consumed after a terminal operation is executed.
Every Terminal operation will end the stream and produces a result.
Below are the list of Terminal operations
In this post, we learned about Java 8 Stream pipelines and basic details of Source, intermediate and terminal operations.
Reference : Official documentation
Please leave a comment and give us a thumbs up!