Say I have an Integer list and I'm using Java 8 forEach method on the list to double its values. Say I have the following code:
List<Integer> l = Arrays.asList(2,3,6,1,9);
l.forEach(p->p*=2);
As forEach method take Consumer and calls it accept methos. I print the list after runnig the above code and the original list doesn't change.
As far as I understand Stream doesn't alter the source but here I just call accept method on each element...
Thank u in advace
The forEach is designed to be a terminal operation and yes - you can't do anything after you call it. The idiomatic way would be to apply a transformation first and then collect() everything to the desired data structure. The transformation can be performed using map which is designed for non-mutating operations.
Because ArrayList is not a thread-safe collection.
The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
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, and which relies on the prevailing rule of non-interference.
The method forEach
only iterates through the elements of the list without changing them, If you want to change the elements, you can use the method replaceAll
:
List<Integer> l = Arrays.asList(2,3,6,1,9);
l.replaceAll(p->p*2);
The reason that forEach does not mutate the list comes down to the specification:
The javadoc for forEach
says:
default void forEach(Consumer<? super T> action)
..... The default implementation behaves as if:
for (T t : this) action.accept(t);
As you can see:
action
is a Consumer
; i.e. it doesn't generate a value.this
collection to be updated.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