Q55: How does the Java Stream API distinguish between Intermediate and Terminal Operations?
- Intermediate Operations (
filter,map,flatMap,sorted):- Return a new Stream.
- Lazy evaluation: No element processing occurs until a terminal operation is invoked.
- Terminal Operations (
collect,forEach,reduce,findFirst):- Trigger element processing pipeline execution.
- Produce a non-Stream result or side-effect, closing the Stream pipeline.
Stream Pipeline Execution
List<String> names = List.of("Alice", "Bob", "Charlie");
// Intermediate operations evaluated ONLY when count() terminal operation fires
long count = names.stream()
.filter(name -> name.length() > 3) // Intermediate
.map(String::toUpperCase) // Intermediate
.count(); // Terminal (triggers execution)💡 Filter and map steps execute lazily during the final count() processing pass.
Key Takeaways
- Intermediate operations are lazy and return a new Stream.
- Terminal operations trigger pipeline evaluation and close the stream.
Knowledge Check
What happens if a Stream pipeline contains multiple intermediate operations but NO terminal operation?