Java Stream forEach() and forEachOrdered() Methods

Filed Under: Java
  • 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


void forEach(Consumer<? super T> action)

void forEachOrdered(Consumer<? super T> action);

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.


jshell> Stream<Integer> streamNumbers = Stream.of(1, 2, 3, 4);
streamNumbers ==> java.util.stream.ReferencePipeline$Head@5a10411

jshell> streamNumbers.forEach(System.out::println);
1
2
3
4

jshell> 

Parallel Stream forEach() Example

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


jshell> List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);
list ==> [1, 2, 3, 4, 5, 6, 7]

jshell> list.parallelStream().forEach(System.out::println);
5
4
1
3
2
7
6

jshell> 
Stream ForEach Example

Stream forEach() 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.


jshell> List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);
list ==> [1, 2, 3, 4, 5, 6, 7]

jshell> list.parallelStream().forEachOrdered(System.out::println);
1
2
3
4
5
6
7

jshell> 

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

Reference

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages