jimmayhem
jimmayhem

Reputation: 405

Does it matter where to place parallel() call in the stream pipeline?

For instance, parallel() before filter()

Stream.of(...)
      .parallel()
      .filter(...)
      .forEach(...);

and parallel() after filter()

Stream.of(...)
      .filter(...)
      .parallel()
      .forEach(...);

Does order of calling parallel() affect the stream?

Upvotes: 4

Views: 225

Answers (1)

Jeroen Steenbeeke
Jeroen Steenbeeke

Reputation: 4048

It does not matter where you place parallel(). A stream is not evaluated until a terminal operation (in your case forEach) is called.

From the Javadoc:

Returns an equivalent stream that is parallel. May return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel. This is an intermediate operation.

The only situation in which the order matters is if you're also calling sequential, in which case the following applies:

The most recent sequential or parallel mode setting applies to the execution of the entire stream pipeline.

For more information see the relevant Javadoc

Upvotes: 6

Related Questions