This is a example: code A:
files.forEach(f -> {
//TODO
});
and another code B may use on this way:
files.stream().forEach(f -> { });
What is the difference between both, with stream()
and no stream()
?
The definition of Stream.forEach allows for the elements to be processed in any order -- even for sequential streams. (For parallel streams, Stream.forEach will very likely process elements out-of-order.) Iterable.forEach gets an Iterator from the source and calls forEachRemaining () on it.
In parallel stream forEach () method may not necessarily respect the order whereas forEachOrdered () will always respect the order. In sequential stream both methods respect the order. So we should use forEachOrdered () method, if we want action to be perform in encounter order in every case whether the stream is sequential or parallel.
4 Answers 4 ActiveOldestVotes 26 Practically speaking, they are mostly the same, but there is a small semantic difference. Code A is defined by Iterable.forEach, whereas code B is defined by Stream.forEach.
It's unlikely to occur with sequential streams, still, it's within the specification for Stream.forEachto execute in some arbitrary order. This does occur frequently in parallel streams. By contrast, Iterable.forEachis always executed in the iteration order of the Iterable, if one is specified.
Practically speaking, they are mostly the same, but there is a small semantic difference.
Code A is defined by Iterable.forEach
, whereas code B is defined by Stream.forEach
. The definition of Stream.forEach
allows for the elements to be processed in any order -- even for sequential streams. (For parallel streams, Stream.forEach
will very likely process elements out-of-order.)
Iterable.forEach
gets an Iterator from the source and calls forEachRemaining()
on it. As far as I can see, all current (JDK 8) implementations of Stream.forEach
on the collections classes will create a Spliterator built from one of the source's Iterators, and will then call forEachRemaining
on that Iterator -- just like Iterable.forEach
does. So they do the same thing, though the streams version has some extra setup overhead.
However, in the future, it's possible that the streams implementation could change so that this is no longer the case.
(If you want to guarantee ordering of processing streams elements, use forEachOrdered()
instead.)
There is no difference in terms of semantics, though the direct implementation without stream
is probably slightly more efficient.
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