VOOZH about

URL: https://www.geeksforgeeks.org/java/stream-foreach-method-java-examples/

⇱ Stream forEach() method in Java with examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stream forEach() method in Java with examples

Last Updated : 23 Jan, 2026

The Stream.forEach(Consumer action) method performs a given action on each element of the stream. It is a terminal operation, which may traverse the stream to produce a result or a side effect.

Example:


Output
12345

Explanation:

  • numbers.stream() creates a stream from the list.
  • forEach(System.out::println) prints each number.

Syntax

void forEach(Consumer<? super T> action)

  • Parameters: "action" a Consumer functional interface defining the operation to perform on each element.
  • Return Value: None (void) - this is a terminal operation.

Example 1: Print Each Element of a Reversely Sorted Integer Stream


Output
10
8
6
4
2

Explanation:

  • sorted(Comparator.reverseOrder()) sorts the elements in descending order.
  • forEach(System.out::println) prints each element of the stream.

Example 2: Print Each Element of a String Stream


Output
GFG
Geeks
for
GeeksforGeeks

Explanation: forEach(System.out::println) applies the print operation to each element.

Example 3: Print Character at Index 1 from Reversely Sorted String Stream


Output
o
e
e
F

Explanation:

  • sorted(Comparator.reverseOrder()) sorts the strings in descending order.
  • flatMap(str -> Stream.of(str.charAt(1))) extracts the character at index 1 from each string.
  • forEach(System.out::println) prints each extracted character.
Comment