Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between iterable.forEach() and iterable.stream().forEach() [duplicate]

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..)?

like image 620
jlb Avatar asked May 30 '14 12:05

jlb


People also ask

What is the difference between forEach and stream forEach?

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.

What is the difference between forEach and forEach in collection?

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.

What does the forEach () method on Iterable do?

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).

What is the difference between forEach and forEachOrdered?

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.


1 Answers

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.

like image 86
Stuart Marks Avatar answered Oct 14 '22 12:10

Stuart Marks