Learnitweb

Stream forEachOrdered method in Java with example

Many people have written us to explain the use of this method. Many people have confusion about the use of this method and how this method is different from forEach method. forEachOrdered method is provided my Stream interface in Java 8.

Syntax

void forEachOrdered(Consumer<? super T> action)

Official documentation states the following about this method:

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

This is a terminal operation.

In the above statement, term ‘encounter order’ is very important. And elements are processed in the encounter order.

To better understand the use of this method in comparison to forEach method, we’ll use this method to iterate elements of a parallel stream.

In the following example, we are iterating elements of a parallel stream using forEach method. Please note that the output in your case could be different as we are using parallel stream.

Order not guaranteed – Using forEach to iterate elements of parallel stream

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ForEachExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<Integer> listOfNumbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
    	
    	//Create a parallel stream from list 
    	Stream<Integer> stream = listOfNumbers.parallelStream();
    	
    	//using forEach to iterate elements
    	stream.forEach(System.out::println);
    }
}

Output

6
5
8
3
4
2
1
9
7

As you can see the result of iteration is not the same as the order of elements in the list. Every time you execute the program, it is possible that you get a different output every time.

Sometimes it is important to maintain the order while processing the elements. In such case, forEachOrdered method can be used.

Order guaranteed – Using forEachOrdered method

In this following example, we are using forEachOrdered method instead of forEach method.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ForEachOrderedExample {
    public static void main(String[] args) {
    	//Create a list for demo purpose
    	List<Integer> listOfNumbers = Arrays.asList(1,2,3,4,5,6,7,8,9);
    	
    	//Create a parallel stream from list 
    	
    	Stream<Integer> stream = listOfNumbers.parallelStream();
    	
    	//using forEach to iterate elements
    	stream.forEachOrdered(System.out::println);
    }
}

Output

1
2
3
4
5
6
7
8
9

Note that the elements in the output are in the same order as in the list. Every time you run this program and you will get the same output. This order can not be ensured when you use forEach method.

We use forEachOrdered method when processing order of elements matters.

In this tutorial, we discussed forEachOrdered method and how this method is different from forEach method.