I have a question about the difference between Arraylist.forEach()
and Arraylist.replaceAll()
. I know that Arraylist.forEach()
is used to perform an action for each element in the list, but it seems that Arraylist.replaceAll()
does the exact same thing. But for some reason, when you decide to do a.forEach(e -> e.concat("test");
assuming a is an Arraylist of Strings, the Arraylist does not concatenate “test” to the end of each String in the Arraylist. However, if you do a.replaceAll(e -> e.concat("test");
, the concatenation works. Why is this the case? An example of what I am talking about is in this image:
.
The answer is B, but C seems to make the most sense to me. Thanks for the help.
Advertisement
Answer
concat
returns a new string, but forEach
ignores the return value of the lambda expression. (Its declared parameter is a Consumer
, which has no return value.)
replaceAll
puts the return value from its function back into the list. That is what it is for.