It looks like I can call list.forEach(a -> a.stuff())
directly on my collection, instead of list.stream().forEach(a -> a.stuff())
. When would I use one over the other (parallelStream()
aside..)?
The reason for the different results is that forEach() used directly on the list uses the custom iterator, while stream(). forEach() simply takes elements one by one from the list, ignoring the iterator.
forEach() uses the collections iterator. Unlike Collection. forEach() it does not execute in any specific order, i.e. the order is not defined. If always execute in the iteration order of iterable, if one is specified.
forEach. Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified).
The difference between forEachOrdered() and forEach() methods is that forEachOrdered() will always perform given action in encounter order of elements in stream whereas forEach() method is non-deterministic.
There are a few differences:
Iterable.forEach
guarantees processing in iteration order, if it's defined for the Iterable. (Iteration order is generally well-defined for Lists.) Stream.forEach
does not; one must use Stream.forEachOrdered
instead.
Iterable.forEach
may permit side effects on the underlying data structure. Although many collections' iterators will throw ConcurrentModificationException
if the collection is modified during iteration, some collections' iterators explicitly permit it. See CopyOnWriteArrayList
, for example. By contrast, stream operations in general must not interfere with the stream source.
If the Iterable is a synchronized wrapper collection, for example, from Collections.synchronizedList()
, a call to forEach
on it will hold its lock during the entire iteration. This will prevent other threads from modifying the collection during the iteration, ensuring that the iteration sees a consistent view of the collection, and preventing ConcurrentModificationException
. (This will also prevent other threads from reading the collection during the iteration.) This is not the case for streams. There is nothing to prevent the collection from being modified during the stream operation, and if modification does occur, the result is undefined.
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