Java Stream forEach()

Java Stream forEach() method is used to iterate over all the elements of the given Stream and to perform an Consumer action on each element of the Stream.

The forEach() is a more concise way to write the for-each loop statements.

1. Stream forEach() Method

1.1. Method Syntax

The forEach() method syntax is as follows:

void forEach(Consumer<? super T> action)

Consumer is a functional interface and action represents a non-interfering action to be performed on each element in the Stream. It accepts an input and returns no result.

1.2. Description

  • The forEach() method is a terminal operation. It means that it does not return an output of type Stream.
  • After forEach() is performed, the stream pipeline is considered consumed, and Stream can no longer be used.
  • If we need to traverse the same data source again (the collection backing the Stream), we must return to the data source to get a new stream.
  • For parallel streams, the forEach() operation does not guarantee the order of elements in the stream, as doing so would sacrifice the benefit of parallelism.
  • If the provided Consumer action accesses the shared state between the Stream elements the action is responsible for providing the required synchronization.

2. Stream forEach() Examples

Example 1: Traversing the elements of a Stream and printing them

In this Java example, we are iterating over a Stream of Integers and printing all the integers to the standard output.

List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); 
Consumer<Integer> action = System.out::println;
    .forEach( action );

Note that we can write the above iteration using the enhanced for-loop as well.

for (Integer i : list) {

Example 2: Traversing the elements in reverse order and printing them

Java example to iterate over stream elements and print them in reverse order.

List<Integer> list = Arrays.asList(2, 4, 6, 8, 10);

Program output.


3. Conclusion

In this tutorial, we learned to use the forEach() method to iterate through all the elements of a Stream.

Though we can use the enhanced for-each loop for the iteration, the primary difference between the forEach() method and for-each loop is that the for-each loop is an external iterator, whereas the new forEach() method is an internal iterator.

Drop me your questions related to Stream forEach() method in Java Stream API.

Happy Learning !!

Sourcecode on Github


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode