2

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?

Anton Sarov
  • 3,712
  • 3
  • 31
  • 48

3 Answers3

4

map is the better choice for this, because you're not trying to do anything with the strings yet, just map them to different strings.

forEach is designed to be the "final operation." As such, it doesn't return anything, and is all about mutating some state -- though not necessarily that of the original collection. For instance, you might use it to write elements to a file, having used other constructs (including map) to get those elements.

yshavit
  • 42,327
  • 7
  • 87
  • 124
3

forEach terminates the stream and is exectued because of the side effect of the called Cosumer. It does not necessarily mutate the stream members.

map maps each stream element to a different value/object using a provided Function. A Stream <R> is returned on which more steps can act.

1

The forEach terminal operation might be useful in several cases: when you want to collect into some older class for which you don't have a proper collector or when you don't want to collect at all, but send you data somewhere outside (write into the database, print into OutputStream, etc.). There are many cases when the best way is to use both map (as intermediate operation) and forEach (as terminal operation).

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334