Why filter() after flatMap() is “not completely” lazy in Java streams?

前端 未结 7 1155
误落风尘
误落风尘 2020-11-22 08:17

I have the following sample code:

System.out.println(
       \"Result: \" +
        Stream.of(1, 2, 3)
                .filter(i -> {
                             


        
7条回答
  •  隐瞒了意图╮
    2020-11-22 08:52

    The elements of the input stream are consumed lazily one by one. The first element, 1, is transformed by the two flatMaps 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.

提交回复
热议问题