Skip to content
Tutorials Center
My learning

Topics

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.

Java
names.stream().filter(n -> n.startsWith("A")).forEach(System.out::println);

Try it

Java forEach and forEachOrdered

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.

Java Side effects: collect instead

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

Java
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, toList or count to compute results. forEach is for effects that leave the pipeline: printing, logging, sending.
  • Shared state: adding to an ArrayList from a parallel forEach is a data race. Use collect, or a thread-safe collection if you must.
  • No break or continue: return in the lambda only skips the current element. To stop early use takeWhile, limit or a loop.
  • Checked exceptions cannot propagate from the lambda; wrap them.
  • forEachOrdered guarantees 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: forEach does not change the source; to modify a list in place use replaceAll or removeIf.