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);
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.
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() .
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.
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.
Stream.flatMap( )
causes breaking of short-circuiting of terminal operations -
it was a bug that was fixed starting from Java 10.
laziness has changed in case of flatMap
, until java-10, flatMap
was never lazy. see JDK-8075939
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With