Junior — Middle
How to distinguish operators that perform intermediate actions from those that terminate the data stream?
sobes.tech AI
Answer from AI
In stream data (Streams), operators are divided into intermediate and terminal:
-
Intermediate operators return a new stream and allow chaining operations. They are lazy — they do not execute until a terminal operator is called. Examples:
map(),filter(),sorted(). -
Terminal operators complete the stream, perform computations, and return a result or side effect. After their invocation, the stream is considered closed. Examples:
collect(),forEach(),reduce(),count().
To distinguish:
- If the operator returns a Stream — it is intermediate.
- If it returns something other than Stream (e.g., a collection, a number, void) — it is terminal.
Example:
Stream.of(1, 2, 3)
.filter(n -> n > 1) // intermediate
.map(n -> n * 2) // intermediate
.forEach(System.out::println); // terminal