Module: | Multithreading, Collections & I/O Streams
Q66: Consider the following statements regarding Stream Laziness and Short-Circuiting:
1. The Java Streams API employs "lazy evaluation," mathematically guaranteeing that intermediate operations are never executed until a terminal operation is explicitly invoked.
2. Short-circuiting terminal operations like findFirst() or anyMatch() can successfully terminate an infinite stream and return a definitive result without processing every single element.
3. A single instantiated Java Stream object can be safely reused to execute multiple different terminal operations as long as they are called sequentially on the exact same thread.
Which of the above statements is/are correct?
2. Short-circuiting terminal operations like findFirst() or anyMatch() can successfully terminate an infinite stream and return a definitive result without processing every single element.
3. A single instantiated Java Stream object can be safely reused to execute multiple different terminal operations as long as they are called sequentially on the exact same thread.
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 Stream objects are strictly single-use constructs. Once a terminal operation is executed, the stream is permanently closed and destroyed; it cannot be reused on any thread.Historical/Related Context: Lazy evaluation was adopted from functional languages.
In a legacy Java loop, if you needed the first even number from a list of 10 million items, you might mistakenly process all 10 million items to find all evens before picking the first.
Streams intelligently fuse filter() and findFirst(), processing only until the first match is hit, saving immense CPU cycles.
Causal Reasoning: Laziness (Statement 1) is a critical performance mechanism.
Because intermediate operations do not execute immediately, the JVM can look at the entire pipeline once the terminal operation is called and structurally merge the operations (e.g., merging a filter and a map into a single pass over the data) to dramatically reduce execution overhead.