Let's say you have a collection with some strings and you want to return the first two characters of each string (or some other manipulation...).
In Java 8 for this case you can use either the map
or the forEach
methods on the stream() which you get from the collection (maybe something else but that is not important right now).
Personally I would use the map
primarily because I associate forEach
with mutating the collection and I want to avoid this. I also created a really small test regarding the performance but could not see any improvements when using forEach
(I perfectly understand that small tests cannot give reliable results but still).
So what are the use-cases where one should choose forEach
?