can someone tell me What is the difference between intermediate and terminal operations for Stream
?
Stream
operations are combined into pipelines to process streams. All operations are either intermediate or terminal ..means?.
1) The main difference between intermediate and terminal operations is that intermediate operations return a stream as a result and terminal operations return non-stream values like primitive or object or collection or may not return anything.
Intermediate operations process the current stream of data (if any) and then return a new stream. Terminal operations as the name suggests are the last in the pipeline of operations performed on a stream.
Terminal Operations means services provided at a port, rail or road terminal or station including cargo handling, storing and delivery of cargo to vessels, trains and vehicles, handling of passengers howsoever and services related thereto; Sample 1Sample 2.
Stream. Intermediate operators do not execute until a terminal operation is invoked, i.e. they are not executed until a result of processing is actually needed. We will be discussing a few of the important and most frequently used: filter(predicate) Method. sorted() Method.
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.
As per javadoc:
map(MapperFn)
or filter(Predicate)
count()
or forEach(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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With