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

前端 未结 7 1229
误落风尘
误落风尘 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:46

    Today I also stumbled up on this bug. Behavior is not so strait forward, cause simple case, like below, is working fine, but similar production code doesn't work.

     stream(spliterator).map(o -> o).flatMap(Stream::of).flatMap(Stream::of).findAny()
    

    For guys who cannot wait another couple years for migration to JDK-10 there is a alternative true lazy stream. It doesn't support parallel. It was dedicated for JavaScript translation, but it worked out for me, cause interface is the same.

    StreamHelper is collection based, but it is easy to adapt Spliterator.

    https://github.com/yaitskov/j4ts/blob/stream/src/main/java/javaemul/internal/stream/StreamHelper.java

提交回复
热议问题