forEach not modify java(8) collection-ThrowExceptions

Exception or error:

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);

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

How to solve:

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)

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.


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);


Try to use map insted of forEach to alter original List.

List<Integer> list = Arrays.asList(2,3,6,1,9); -> p * 2).collect(Collectors.toList());

Leave a Reply

Your email address will not be published. Required fields are marked *