Intermediate and Terminal Operation in Java 8 Stream API
The java stream API provides a functional approach to processing collection of objects. Stream API added in java 8.
Stream operations are divided into intermediate and terminal operations and are combined to form stream pipelines.
A Stream pipeline is source such as array, collection, I/O channel or generator function.
In Java 8, Stream API have two types of operations :-
- Intermediate Operation
- Terminal Operation
1. Intermediate Operation
Intermediate operations are lazy operations means it is always returns new Stream. Intermediate operations does not produce result.
Following are Intermediates methods of stream :-
- filter()
- map()
- sorted()
- flatMap()
- Distinct()
- limit()
- peek()
Lazy operations are allows significant efficiencies. In a pipeline such as filtering, mapping and summing can be fused into a single pass on the data, with minimal intermediate state.
Laziness also avoids examining the all data when it is not necessary.
Intermediate operations are also divided into two operations :-
- Stateless
- Stateful
Stateless Operation :-
Stateless operations such as filter and map, retain no state for previously seen element when processing new element. Each element can be processed independently.
Stateful Operation :-
Stateful operations such as Distinct and Sorted, may incorporate state from previously seen elements when processing new elements.
Stateful operations may need to process entire input before producing result. For example, Sorting all given elements.
See example of Intermediate Operation :-
As you can see Intermediate operation returns Stream, it does not produce result.
2. Terminal Operation
Terminal operations are traverse the stream and produce the result.
After the performed Terminal operation, the stream pipeline is considered consumed, and can no longer used.
If we need to traverse the same data source again, we must return to the data source to get a new stream.
In almost all cases, terminal operations are eager.
Following are Terminal Operations :-
See example of Terminal Operation :-
Comments
Post a Comment