Module: | Multithreading, Collections & I/O Streams
Q65: Consider the following statements regarding the Stream API's operation phases:
1. Intermediate operations, such as filter() and map(), inherently return a new Stream, allowing developers to chain multiple operations together in a fluid pipeline.
2. Terminal operations, such as collect() and reduce(), finalize the pipeline and completely consume the stream, making it permanently inaccessible for future operations.
3. Intermediate operations are eagerly evaluated, meaning the JVM executes the data filtering logic the exact millisecond the filter() method is called in the code sequence.
Which of the above statements is/are correct?
2. Terminal operations, such as collect() and reduce(), finalize the pipeline and completely consume the stream, making it permanently inaccessible for future operations.
3. Intermediate operations are eagerly evaluated, meaning the JVM executes the data filtering logic the exact millisecond the filter() method is called in the code sequence.
Which of the above statements is/are correct?
✅ Correct Answer: A
🎯 Quick Answer:
The correct combination is 1 and 2. Statement 3 is incorrect because Intermediate operations are strictly "lazy." They do not execute any data processing when called; they merely queue up the instructions. Execution only occurs when a Terminal operation is ultimately invoked.Structural Breakdown: A Stream pipeline requires exactly three components: A Source (like an ArrayList), zero or more Intermediate Operations (transformations), and exactly one Terminal Operation (the catalyst that produces the final result). Historical/Related Context: Before Streams, developers used iterative for loops to filter data, which meant creating multiple temporary ArrayLists to hold intermediate states, wasting massive amounts of Heap memory.
Streams solved this by processing the data functionally on-the-fly without permanently altering the underlying source collection.
Causal Reasoning: Streams must be consumed by a terminal operation (Statement 2) because a stream does not store data; it simply transports it.
Once the collect() method pulls the elements through the pipeline and packs them into a final List, the stream's transport mechanism is mathematically exhausted.
Any attempt to reuse it throws an IllegalStateException.