Java Stream : forEachOrdered() vs forEach()
June 13, 2020
On this page we will provide differences between Stream.forEachOrdered()
and Stream.forEach()
methods. Both methods perform an action as Consumer
. The difference between forEachOrdered()
and forEach()
methods is that forEachOrdered()
will always perform given action in encounter order of elements in stream whereas forEach()
method is non-deterministic. In parallel stream forEach()
method may not necessarily respect the order whereas forEachOrdered()
will always respect the order. In sequential stream both methods respect the order. So we should use forEachOrdered()
method, if we want action to be perform in encounter order in every case whether the stream is sequential or parallel. If the stream is sequential, we can use any method to respect order. But if stream can be parallel too, then we should use forEachOrdered()
method to respect the order.
Stream.forEach()
Find theforEach
method declaration.
void forEach(Consumer<? super T> action)
Consumer
for each element of this stream.
2. This is a terminal operation.
3. The behavior of this operation is non-deterministic.
4. In parallel operation this method does not guarantee to respect the encounter order.
Stream.forEachOrdered()
Find theforEachOrdered
method declaration.
void forEachOrdered(Consumer<? super T> action)
Consumer
for each element of this stream in the encounter order of this stream if the stream has a defined encounter order.
2. This is a terminal operation.
3. This method guarantees to respect the encounter order in sequential and parallel streams both.
Using Sequential Stream
In sequential streamforEach
and forEachOrdered
both method will perform action in encounter order.
Find the code for
forEach
method.
Stream.of("A","B","C", "D") .forEach(e -> System.out.println(e));
Find the code for
forEachOrdered
method.
Stream.of("A","B","C", "D") .forEachOrdered(e -> System.out.println(e));
If order matters, it would be better to always use
forEachOrdered
method.
Using Parallel Stream
In parallel streamforEach
does not guarantee encounter order.
Stream.of("A","B","C", "D") .parallel() .forEach(e -> System.out.println(e));
The
forEachOrdered
method always guarantee the encounter order.
Stream.of("A","B","C", "D") .parallel() .forEachOrdered(e -> System.out.println(e));