Java Stream forEach() and forEachOrdered() Methods With Examples

Java Stream forEach() and forEachOrdered() are terminal operations.

  • The forEach() method is used to perform an action on each elements of the stream.
  • If the forEach() method is used with parallel stream, the encounter order is not maintained. The action will be performed on each element, but their order will not be fixed.
  • If you want to perform some action on stream elements in the encounter order, you should use forEachOrdered() method.
  • The underlying collection must have encounter order, otherwise forEachOrdered() will not be able to respect that. So using it with TreeSet or TreeMap is useless.
  • The forEachOrdered() action is executed on each stream element one by one, so it’s a bit slower than forEach() method.
  • Using forEachOrdered() on a parallel stream doesn’t provide benefits of parallel stream, so using it with a parallel stream doesn’t make much sense.

Java Stream forEach() and forEachOrdered() Methods Signature

Consumer is a Functional Interface. It represents an operation that accepts a single input argument and returns no result.

Stream forEach() Example

Let’s look at a simple example to print all the elements of the stream.

Parallel Stream forEach() Example

Let’s see what happens when we use forEach() with a parallel stream.

Stream for Each() Example

Notice that the stream elements are getting in random order. The encounter order of the elements is not respected when forEach() is performing an action on stream elements.

Parallel Stream forEachOrdered() Example

Let’s see what happens when we use forEachOrdered() with a parallel stream of list elements.

It’s clear that the encounter order of the stream is maintained.


By admin

Leave a Reply

%d bloggers like this: