I was confused about the difference between map()
and forEach()
method in java8 stream. For instance,
List strings =
The documentation for each instance method of Stream
states whether the method is an intermediate operation, or a terminal operation. Only terminal operations will cause the stream to be evaluated. Intermediate operations may not be performed unless required by a downstream terminal operation.
This can improve efficiency, especially when the terminal operation is a short-circuit operation, like findAny()
. A pipeline with a complex set of intermediate operations doesn't need to be executed for additional elements after a matching element has been found.
In your case, forEach()
is a terminal operation; it causes the pipeline to be executed. map()
is an intermediate operation; it doesn't have to do anything unless required by a downstream terminal operation.