How do terminal and non-terminal operations in Stream API differ in their functions and purpose?
sobes.tech AI
Answer from AI
In the Stream API, terminal and non-terminal operations differ in their purpose and behavior:
-
Non-terminal operations (intermediate) are operations that return a new stream and allow building a chain of transformations. They are lazy, meaning they are not executed immediately but only when a terminal operation is invoked. Examples:
filter(),map(),sorted(),distinct(). -
Terminal operations (terminal) complete the chain of operations and trigger data processing. They return a result (for example, a collection, a number, or void). After a terminal operation, the stream is considered closed and cannot be reused. Examples:
collect(),forEach(),reduce(),count().
Example:
List<String> result = list.stream()
.filter(s -> s.startsWith("A")) // non-terminal
.map(String::toUpperCase) // non-terminal
.collect(Collectors.toList()); // terminal
Here, filtering and transformation are not executed immediately but only when collect() is called, which triggers processing and returns the final list.