Junior — Middle
What is the difference between intermediate operators and terminal operators in data streams or sequences?
sobes.tech AI
Answer from AI
Intermediate operators (intermediate) in data streams (Streams in Java) are operations that return a new stream and allow chaining calls. They are lazy, meaning they do not execute immediately but only when a terminal operator is invoked. Examples: filter(), map(), sorted().
Terminal operators (terminal) are operations that complete the stream processing, return a result or side effect, and trigger the execution of the entire chain. After a terminal operator, the stream cannot be used. Examples: collect(), forEach(), reduce(), count().
Example:
List<String> list = List.of("a", "bb", "ccc");
long count = list.stream()
.filter(s -> s.length() > 1) // intermediate operator
.count(); // terminal operator
Here, filter is not executed immediately but only when count is called.