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 reason that forEach does not mutate the list comes down to the specification:
The javadoc for
default void forEach(Consumer<? super T> action)
….. The default implementation behaves as if:
for (T t : this) action.accept(t);
As you can see:
Consumer; i.e. it doesn’t generate a value.
- The semantics don’t allow for the
thiscollection to be updated.
forEach only iterates through the elements of the list without changing them, If you want to change the elements, you can use the method
List<Integer> l = Arrays.asList(2,3,6,1,9); l.replaceAll(p->p*2);
Try to use
map insted of
forEach to alter original
List<Integer> list = Arrays.asList(2,3,6,1,9); list=list.stream().map(p -> p * 2).collect(Collectors.toList()); System.out.println(list);