Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach not modify java(8) collection

Tags:

java

java-8

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

like image 758
user1409534 Avatar asked May 25 '14 05:05

user1409534


People also ask

How do you collect after forEach?

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.

Why is list Parallelstream () forEach () not processing all the elements in the list in Java?

Because ArrayList is not a thread-safe collection.

Why forEach method is added to each 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.

What is the difference between forEach and stream forEach?

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.


2 Answers

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);
like image 184
nosid Avatar answered Oct 18 '22 21:10

nosid


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:

  • The action is a Consumer; i.e. it doesn't generate a value.
  • The semantics don't allow for the this collection to be updated.
like image 19
Stephen C Avatar answered Oct 18 '22 22:10

Stephen C