I have the following sample code:
System.out.println(
\"Result: \" +
Stream.of(1, 2, 3)
.filter(i -> {
The elements of the input stream are consumed lazily one by one. The first element, 1
, is transformed by the two flatMap
s into the stream -1, 0, 1, 0, 1, 2, 1, 2, 3
, so that entire stream corresponds to just the first input element. The nested streams are eagerly materialized by the pipeline, then flattened, then fed to the filter
stage. This explains your output.
The above does not stem from a fundamental limitation, but it would probably make things much more complicated to get full-blown laziness for nested streams. I suspect it would be an even greater challenge to make it performant.
For comparison, Clojure's lazy seqs get another layer of wrapping for each such level of nesting. Due to this design, the operations may even fail with StackOverflowError
when nesting is exercised to the extreme.