22

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

3 Answers 3

34

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

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.
3
  • Thank u for your answer. But if T is some object reference and I change its content within forEach loop I should see its new content. May 25, 2014 at 6:33
  • 2
    No, that's not true with or without lambdas, and never has been. May 25, 2014 at 8:15
  • @user1409534 - You could change the contents of object that the object reference points to, but that does not update the list. To update the list (in the way you are attempting to do), you would need to replace the object reference in the list with another one. You can't do that with a forEach(). And certainly the lambda won't / can't do it.
    – Stephen C
    May 25, 2014 at 9:55
11

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

List<Integer> list = Arrays.asList(2,3,6,1,9);
list=list.stream().map(p -> p * 2).collect(Collectors.toList());
System.out.println(list);
2
  • 12
    That creates a new list, it doesn't mutate the existing list. It's probably better that way, but it's still important to be aware of the distinction. May 25, 2014 at 5:27
  • Thank u for your answer. I am aware of using map in order to get new collection and map metod of stream. I don't understand why forEach metod on collection doesn't alter the element if its only calling accept metod of the given lambda? May 25, 2014 at 5:32

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.