Skip to content
Advertisement

What is the difference between intermediate and terminal operations?

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?.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement