18

Consider this code:

public static void main(String[] args) {
    Stream.iterate(1, i -> i + 1)
            .flatMap(i -> Stream.of(i, i, i))
            .peek(System.out::println)
            .limit(4)
            .forEach(i -> {});
}

The output in Java 8:

1
1
1
2
2
2

And in Java 11:

1
1
1
2

Was this a bug or intended behaviour in Java 8 that was changed in 11?

The above code is just an example to demonstrate the different behaviours, but a more serious implication of the difference is that the following code prints 1,2,3 in Java 11 but goes into an infinite loop in Java 8:

    Stream.iterate(0, i -> i + 10)
            .flatMap(i -> Stream.iterate(i + 1, j -> j + 1))
            .limit(3)
            .forEach(System.out::println);
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42

3 Answers3

10

Stream.flatMap( ) causes breaking of short-circuiting of terminal operations -

it was a bug that was fixed starting from Java 10.

Oleksandr Pyrohov
  • 14,685
  • 6
  • 61
  • 90
7

laziness has changed in case of flatMap, until java-10, flatMap was never lazy. see JDK-8075939

Eugene
  • 117,005
  • 15
  • 201
  • 306
1

It is not a bug but an optimization to make flatMap work in lazy mode.

One of the beautiful feature improvement I can see, as now I can use flatMap in Lazy way, with almost fully supporting functional composition rather than just a chain of function execution (if not lazy).

Functional composition is what really excite me every day when I start writing NEW Java code.

Maybe I'm late to the party..!! :P

miiiii
  • 1,580
  • 1
  • 16
  • 29