Should I use shared mutable variable update in Java 8 Streams
Regardless of whether you use parallel or sequential Stream
, you shouldn't use forEach
when your goal is to generate a List
. Use map
with collect
:
List<String> list2 =
list2.stream()
.map(item -> item.startsWith("A") ? item : "EMPTY")
.collect(Collectors.toList());
Functionally speaking,for the simple cases they are almost the same, but generally speaking, there are some hidden differences:
- Lets start by quoting from Javadoc of
forEach
for iterable use-cases stating that:
performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
and also we can iterate over a collection and perform a given action on each element – by just passing a class that implements the Consumer interface
void forEach(Consumer<? super T> action)
https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-
- The order of
Stream.forEach
is random whileIterable.forEach
is always executed in the iteration order of theIterable
.
- If
Iterable.forEach
is iterating over a synchronized collection,Iterable.forEach
takes the collection's lock once and holds it across all the calls to the action method. The Stream.forEach call uses the collection's spliterator, which does not lock
- The action specified in
Stream.forEach
is required to be non-interfering whileIterable.forEach
is allowed to set values in the underlyingArrayList
without problems.
- In Java, Iterators returned by Collection classes, e.g. ArrayList, HashSet, Vector, etc., are fail fast. This means that if you try to add() or remove() from the underlying data structure while iterating it, you get a
ConcurrentModificationException.
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#fail-fast
More Info:
- What is the difference between .foreach and .stream().foreach?
- What is difference between Collection.stream().forEach() and Collection.forEach()?