Java Stream forEach(action) method is used to iterate over all the elements of the given Stream and to perform an
Consumer action on the each element of the Stream.
1. Stream forEach() Method
1.1. Method Syntax
forEach() method syntax is as follows:
void forEach(Consumer<? super T> action)
forEach()method is a terminal operation. It means that it does not return an output of type
- 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
actionaccesses the shared state between the Stream elements the
actionis responsible for providing the required synchronization.
2. Stream forEach() Example
Example 1: Java program for 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); list.stream() .forEach( System.out::println );
2 4 6 8 10
Example 2: Java program for 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); list.stream() .sorted(Comparator.reverseOrder()) .forEach(System.out::println);
10 8 6 4 2
Drop me your questions related to Stream forEach() method in Java Stream API.
Happy Learning !!