Junior — Middle
What is the difference between intermediate and terminal functions in Stream API, and how do they affect stream execution?
sobes.tech AI
Answer from AI
In the Stream API (for example, in Java), operations are divided into intermediate and terminal.
Intermediate functions:
- Return a new stream, allowing for chaining operations.
- Lazy — they are not executed immediately, only upon calling a terminal operation.
- Examples:
filter(),map(),sorted().
Terminal functions:
- Complete the chain of operations and trigger data processing.
- Return a result (e.g., a collection, a number, void).
- Examples:
collect(),forEach(),reduce().
Impact on execution:
- Intermediate operations accumulate and are not executed until a terminal operation is invoked.
- This allows for optimization, such as performing operations element-wise and interrupting processing if necessary.
Example:
List<String> result = list.stream()
.filter(s -> s.startsWith("A")) // intermediate
.map(String::toUpperCase) // intermediate
.collect(Collectors.toList()); // terminal
Here, filtering and transformation are not executed immediately but only when collect() is called. This improves efficiency and allows building flexible data processing pipelines.