Java Stream forEachOrdered Example

1. Introduction

In this tutorial, we will learn how to use the forEachOrdered() method in the Java Stream API. The forEachOrdered() ensures that the action is applied to the elements of the stream in the order in which they appear in the source, regardless of whether the stream is sequential or parallel.

Key Points

1. forEachOrdered() ensures that the action is applied to the elements of the stream in the order in which they appear in the source, regardless of whether the stream is sequential or parallel.

2. It is a terminal operation that behaves like forEach() but with order constraints.

3. Ideal for output or side effects that need to be ordered, especially useful with parallel streams.

2. Program Steps

1. Create a Stream of elements.

2. Apply the forEachOrdered() method to perform actions on these elements in their encounter order.

3. Observe the ordered effects of the operation.

3. Code Program

import java.util.stream.Stream;

public class StreamForEachOrderedExample {

    public static void main(String[] args) {
        // Creating a parallel stream of strings
        Stream<String> parallelStream = Stream.of("apple", "banana", "cherry", "date", "elderberry").parallel();

        // Using forEachOrdered to print elements in the order they appear in the source
        System.out.println("Elements in order:");
        parallelStream.forEachOrdered(System.out::println);
    }
}

Output:

Elements in order:
apple
banana
cherry
date
elderberry

Explanation:

1. Stream.of("apple", "banana", "cherry", "date", "elderberry").parallel() creates a parallel stream of strings. Parallel streams can process elements in different orders to optimize performance.

2. parallelStream.forEachOrdered(System.out::println) applies forEachOrdered() to ensure that elements are processed in the order they appear in the source array, despite the stream being parallel.

3. Each element is printed in the original order as defined, demonstrating how forEachOrdered() respects the encounter order.

Comments