Home  >  Java 8

Java Stream : forEachOrdered() vs forEach()

By Arvind Rai, 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 the forEach method declaration.
void forEach(Consumer<? super T> action) 
1. Performs an action as 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 the forEachOrdered method declaration.
void forEachOrdered(Consumer<? super T> action) 
1. Performs an action as 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 stream forEach 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)); 
The output is A B C D.
Find the code for forEachOrdered method.
Stream.of("A","B","C", "D")
 .forEachOrdered(e -> System.out.println(e)); 
The output is A B C D.
If order matters, it would be better to always use forEachOrdered method.

Using Parallel Stream

In parallel stream forEach does not guarantee encounter order.
Stream.of("A","B","C", "D")
 .parallel()
 .forEach(e -> System.out.println(e)); 
The output can be C B A D. The output is not necessarily the encounter order.

The forEachOrdered method always guarantee the encounter order.
Stream.of("A","B","C", "D")
 .parallel()
 .forEachOrdered(e -> System.out.println(e)); 
The output is A B C D.

Reference

Java doc: Stream
POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us