Lazy pipelines and fused traversal
Definition:
A lazy stream pipeline runs as a terminal operation traverses its source.
Explanation:
Most stateless intermediate steps can process one element through the pipeline without materializing whole intermediate collections. sorted and some distinct or ordered parallel operations require state.
Illustration image:
Example:
var first = java.util.stream.Stream.of("x","pear","plum")
.filter(s -> s.startsWith("p"))
.map(String::length).findFirst();
System.out.println(first.orElse(0));Expected behavior. The first retained value has length 4; finding it does not require processing all later elements.
Internal working:
Do not depend on side effects in map or peek, which can be skipped by optimizations or early termination.
Interview questions:
Why is peek unsuitable for required side effects?
Short-circuiting or optimization can omit traversal of elements; stream side effects are not a business execution guarantee.