Course contentsShow
← Java
Lesson 1488 of 2,87033. Streams API: Terminal OperationsFree lesson

Understanding forEach as a Terminal Operation

Learn that forEach ends stream processing, triggers evaluation, and returns void unlike intermediate operations.

Understanding forEach as a Terminal Operation

You'll learn how forEach definitively ends stream processing, triggers execution, and returns nothing—unlike intermediate operations that pass data along.

The End of the Line

Think of a stream pipeline as an assembly line: intermediate operations like filter and map set up stations that will transform items, but nothing actually moves until you hit the "start" button. forEach is that start button—and it's also the final destination.

When you call forEach, three critical things happen:

  1. Execution triggers: All those lazy intermediate operations you chained together finally run
  2. Stream terminates: The stream is consumed and cannot be reused
  3. No return value: forEach returns void—it doesn't produce a result you can store or pass along

Why forEach Is Different

Unlike intermediate operations that return a new Stream<T> (allowing further chaining), forEach accepts a Consumer<T> and returns nothing. It exists purely for side effects—performing an action on each element.

List<String> names = List.of("Alice", "Bob", "Charlie");

// forEach is terminal - ends the pipeline
names.stream()
     .filter(name -> name.length() > 3)  // intermediate: lazy
     .map(String::toUpperCase)           // intermediate: lazy
     .forEach(System.out::println);      // terminal: triggers execution
     // .forEach returns void - nothing to chain here!

Once forEach completes, that stream is dead. You cannot add more operations or reuse it.

Key Takeaway:
forEach is a terminal operation that triggers pipeline execution, consumes the stream, and returns void—use it when you need side effects, not when you need a result to process further.