Java Reference ยท Streams and Functional
Java Stream.forEach() method
Reference for Java Stream.forEach() and forEachOrdered(): run an action per element, when order is guaranteed, and why mutating shared state is risky.
forEach() is a terminal operation that performs an action on each element of the stream. It returns nothing; everything it does is a side effect, such as printing or adding to an external structure.
For a sequential stream over an ordered source the action runs in encounter order. For a parallel stream forEach() makes no ordering promise and runs actions on several threads; forEachOrdered() keeps encounter order at some cost to parallelism.
names.stream().filter(n -> n.startsWith("A")).forEach(System.out::println);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
void forEach(Consumer<? super T> action) void forEachOrdered(Consumer<? super T> action)
Also on Iterable.forEach and Map.forEach(BiConsumer) for plain collections.
| Name | Description |
|---|---|
action |
A non-interfering action performed on each element. |
Returns: nothing. Throws: NullPointerException if action is null; any exception thrown by the action propagates and ends the iteration.
Usage notes
- Last resort. Prefer
collect,reduce,toListorcountto compute results.forEachis for effects that leave the pipeline: printing, logging, sending. - Shared state: adding to an
ArrayListfrom a parallelforEachis a data race. Usecollect, or a thread-safe collection if you must. - No
breakorcontinue:returnin the lambda only skips the current element. To stop early usetakeWhile,limitor a loop. - Checked exceptions cannot propagate from the lambda; wrap them.
forEachOrderedguarantees encounter order but can erase the benefit of parallelism.- Plain collections:
list.forEach(...)skips building a stream and is fine when no intermediate steps are needed. - Unmodifiable results:
forEachdoes not change the source; to modify a list in place usereplaceAllorremoveIf.