Java Stream forEach() and forEachOrdered() are terminal operations.
- The forEach() method is used to perform an action on each elements of the stream.
- If the forEach() method is used with parallel stream, the encounter order is not maintained. The action will be performed on each element, but their order will not be fixed.
- If you want to perform some action on stream elements in the encounter order, you should use forEachOrdered() method.
- The underlying collection must have encounter order, otherwise forEachOrdered() will not be able to respect that. So using it with TreeSet or TreeMap is useless.
- The forEachOrdered() action is executed on each stream element one by one, so it’s a bit slower than forEach() method.
- Using forEachOrdered() on a parallel stream doesn’t provide benefits of parallel stream, so using it with a parallel stream doesn’t make much sense.
Java Stream forEach() and forEachOrdered() Methods Signature
1 2 3 4 |
void forEach(Consumer<? super T> action) void forEachOrdered(Consumer&LT;? super T&GT; action); |
Consumer
is a Functional Interface. It represents an operation that accepts a single input argument and returns no result.
Stream forEach() Example
Let’s look at a simple example to print all the elements of the stream.
1 2 3 4 5 6 7 8 9 10 |
jshell> Stream<Integer> streamNumbers = Stream.of(1, 2, 3, 4); streamNumbers ==> java.util.stream.ReferencePipeline$Head@5a10411 jshell> streamNumbers.forEach(System.out::println); 1 2 3 4 jshell> |
Parallel Stream forEach() Example
Let’s see what happens when we use forEach() with a parallel stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
jshell> List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7); list ==> [1, 2, 3, 4, 5, 6, 7] jshell> list.parallelStream().forEach(System.out::println); 5 4 1 3 2 7 6 jshell> <img class="alignnone wp-image-30163 size-full" src="http://all-learning.com/wp-content/uploads/2019/07/stream-forEach-examples.png" alt="stream-forEach-example" width="1200" height="628" /> |
Stream for Each() Example
Notice that the stream elements are getting in random order. The encounter order of the elements is not respected when forEach() is performing an action on stream elements.
Parallel Stream forEachOrdered() Example
Let’s see what happens when we use forEachOrdered() with a parallel stream of list elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
jshell> List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7); list ==> [1, 2, 3, 4, 5, 6, 7] jshell> list.parallelStream().forEachOrdered(System.out::println); 1 2 3 4 5 6 7 jshell> |
It’s clear that the encounter order of the stream is maintained.