What is the forEachOrdered() method of the Stream Interface?

The forEachOrdered method is used to loop through all the elements of the stream and perform a ConsumerIt is a functional interface that represents an operation that accepts a single input and returns no result operation on the element in the encounter order, if the stream has a defined encounter order.

For example, the stream created from list is ordered, so the forEachOrdered will apply the Consumer operation on the elements in the element order present in the stream.

The forEachOrdered method doesn’t return anything; it is a terminal operation.

The Consumer operation is executed on the element before we apply the Consumer operation on the subsequent element. However, the operation can be performed by any thread, selected by the library.

Syntax

void forEachOrdered(Consumer<? super T> action)

Example

import java.util.stream.Stream;
class forEachOrdered {
public static void main( String args[] ) {
Stream<Integer> stream = Stream.of(1,2,3,4,5);
stream.forEachOrdered((number) ->{
System.out.println(number * 2);
});
}
}

In the code above, we used the Stream.of method to create a stream of numbers.

Then, we called the forEachOrdered method on the stream of numbers with the consumer operation to print each number multiplied by 2. The forEachOrdered will loop through elements in the encounter order and print the multiple of 2 of each element on the stream.

Use forEachOrdered on parallel stream

If the stream is parallel, then the Java runtime will split the stream into multiple substreams. Aggregate operations iterate over and process these substreams in parallel, and then combine the results.

When we use forEachOrdered, the elements are looped in the encounter order if the stream has a defined encounter order.

But when we use forEach on the parallelStream, the elements are not looped in encounter order, even if the stream has a defined encounter order.

import java.util.stream.Stream;
import java.util.List;
import java.util.Arrays;
class forEachOrdered {
public static void main( String args[] ) {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Stream<Integer> parallelStream = list.parallelStream();
System.out.println("Using forEachOrdered");
parallelStream.forEachOrdered((number) ->{
System.out.print(number+ " ");
});
System.out.println();
System.out.println("Using forEach");
parallelStream = list.parallelStream();
parallelStream.forEach((number) ->{
System.out.print(number + " ");
});
}
}

In the code above, we have:

  • Created a List of numbers with the Arrays.asList() method, which will return a List from the arguments passed.

  • Created the parallel stream of the List with the parallelStream() method.

  • Called the forEachOrdered method on the parallel stream, which will iterate all the elements of the parallel stream in the encounter order.

  • Called the forEach method on the parallel stream, which will iterate all the elements of the parallel stream in any order.