Stream difference between Java 8 and 11

DodgyCodeException :

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);
Eugene :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35840&siteId=1