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

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

    With regard to breakage with infinite sub-streams, the behavior of flatMap becomes still more surprising when one throws in an intermediate (as opposed to terminal) short-circuiting operation.

    While the following works as expected, printing out the infinite sequence of integers

    Stream.of("x").flatMap(_x -> Stream.iterate(1, i -> i + 1)).forEach(System.out::println);
    

    the following code prints out only the "1", but still does not terminate:

    Stream.of("x").flatMap(_x -> Stream.iterate(1, i -> i + 1)).limit(1).forEach(System.out::println);
    

    I cannot imagine a reading of the spec in which that were not a bug.

    0 讨论(0)
提交回复
热议问题