What is the difference between intermediate and terminal operations?
As per javadoc:
- Intermediate operation will transform a stream into another stream, such as
map(MapperFn)
orfilter(Predicate)
- Terminal operation will produce a result or side-effect, such as
count()
orforEach(Consumer)
Note that all intermediate operations will NOT be executed without a terminal operation at the end. So the pattern will be:
stream()
.intemediateOperation1()
.intemediateOperation2()
...
.intemediateOperationN()
.terminalOperation();
A Stream supports several operations and these operations are divided into intermediate
and terminal
operations.
The distinction between this operations is that an intermediate operation is lazy while a terminal operation is not. When you invoke an intermediate operation on a stream, the operation is not executed immediately. It is executed only when a terminal operation is invoked on that stream. In a way, an intermediate operation is memorized and is recalled as soon as a terminal operation is invoked. You can chain multiple intermediate operations and none of them will do anything until you invoke a terminal operation. At that time, all of the intermediate operations that you invoked earlier will be invoked along with the terminal operation.
All intermediate operations return Stream (can be chained), while terminal operations don't. Intermediate Operations are:
filter(Predicate<T>)
map(Function<T>)
flatMap(Function<T>)
sorted(Comparator<T>)
peek(Consumer<T>)
distinct()
limit(long n)
skip(long n)
Terminal operations produces a non-stream (cannot be chained) result such as primitive value, a collection or no value at all.
Terminal Operations are:
forEach
forEachOrdered
toArray
reduce
collect
min
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny
Last 5 are short-circuiting terminal operations.