forEach not modify java(8) collection
java, java-8
Solution
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.
Problem
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