Java Stream forEach() forEachOrdered() Methods Tutorial

In this section we will learn what the Stream forEach() and forEachOrdered() methods are and how to use them in Java.

What is Java Stream forEach() Method?

The Java Stream forEach() method is used to run a set of instructions for each element in a stream.

Note: this method is terminal and eager.

Java forEach() Method Syntax:

void forEach(Consumer<? super T> action)

forEach() Method Parameters:

The method has one parameter and that is of type Consumer which is a functional interface.

Basically, this method needs a reference to another method.

Here’s the signature of the reference method:

  • It has only one parameter, which is of the same type as the elements in the target stream.
  • The return value of this method is void.

Note: we can create this reference method using the lambda expression or refer to an instance or static method that is already created and has the same signature.

forEach() Method Return Value:

The return value of the forEach() method is void.

Example: using Stream forEach() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
        stream.parallel().forEach(e->System.out.print(e+", "));
    }
}

Output:

3, 6, 8, 2, 7, 9, 5, 1, 4,

Note: because we’ve used the parallel() method to run the stream in parallel, the order of elements is now not the same as it was when stream started.

What is Java Stream forEachOrdered() Method?

The Java Stream forEachOrdered() method is also used to run a set of instructions for each element in a stream.

But the fundamental difference of this method compared to the forEach() is that this one preserves the order of elements in the stream even if the stream is running in parallel.

Note: the method is terminal and eager.

Java forEachOrdered() Method Syntax:

void forEachOrdered(Consumer<? super T> action)

forEachOrdered() Method Parameters:

The method has one parameter and that is of type Consumer which is a functional interface.

Basically, this method needs a reference to another method.

Here’s the signature of the reference method:

  • It has only one parameter, which is of the same type as the elements in the target stream.
  • The return value of this method is void.

Note: we can create this reference method using the lambda expression or refer to an instance or static method that is already created and has the same signature.

forEachOrdered() Method Return Value:

The return value of this method is void.

Example: using Stream forEachOrdered() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
        stream.parallel().forEachOrdered(e->System.out.print(e+", "));
    }
}

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9,

Leave a Reply