Learn to use Stream.forEach(Consumer action) method to traverse all the elements of stream and performs an action for each element of this stream.
1. Stream.forEach() method
- This is a terminal operation.
- After forEach() is performed, the stream pipeline is considered consumed, and can no longer be used.
- If we need to traverse the same data source again, we must return to the data source to get a new stream.
- For parallel stream pipelines,
forEach()operation does not guarantee the order of elements in the stream, as doing so would sacrifice the benefit of parallelism.
- If the provided action (method argument) accesses shared state between elements, it is responsible for providing the required synchronization.
2. forEach() method syntax
The method syntax is as follows:
void forEach(Consumer<? super T> action)
3. Stream forEach() method example
3.1. Traverse and print all elements
Java example to iterate over stream elements and print them.
List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); list.stream().forEach( System.out::println );
2 4 6 8 10
3.2. Traverse and print all elements in reverse order
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 !!