Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream difference between Java 8 and 11 [duplicate]

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);
like image 268
DodgyCodeException Avatar asked Mar 15 '19 11:03

DodgyCodeException


People also ask

Is Java 8 stream faster than for loop?

Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances. The point to take home is that sequential streams are no faster than loops.

How do I find duplicates in a string in Java 8?

In Java 8 Stream, filter with Set. Add() is the fastest algorithm to find duplicate elements, because it loops only one time. Set<T> items = new HashSet<>(); return list. stream() .

How do I filter duplicates in Java 8?

You can use the Stream. distinct() method to remove duplicates from a Stream in Java 8 and beyond. The distinct() method behaves like a distinct clause of SQL, which eliminates duplicate rows from the result set.

What is the function used to duplicate a stream?

CopyTo(Stream) Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.


3 Answers

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

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

like image 71
Oleksandr Pyrohov Avatar answered Nov 07 '22 13:11

Oleksandr Pyrohov


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

like image 33
Eugene Avatar answered Nov 07 '22 13:11

Eugene


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

like image 37
miiiii Avatar answered Nov 07 '22 13:11

miiiii