Stream forEach() method in Java with examples (original) (raw)
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:
Java `
import java.util.Arrays; import java.util.List;
public class Main { public static void main(String[] args) { List numbers = Arrays.asList(1, 2, 3, 4, 5);
// Print each number in the list using forEach
numbers.stream().forEach(System.out::print);
}}
`
**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
Java `
import java.util.*;
class GFG { public static void main(String[] args) { List list = Arrays.asList(2, 4, 6, 8, 10);
// Sort in reverse order and print each element
list.stream()
.sorted(Comparator.reverseOrder())
.forEach(System.out::println);
}}
`
**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
Java `
import java.util.*;
class GFG { public static void main(String[] args) { List list = Arrays.asList("GFG", "Geeks", "for", "GeeksforGeeks");
// Print each string in the stream
list.stream().forEach(System.out::println);
}}
`
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
Java `
import java.util.*; import java.util.stream.Stream;
class GFG { public static void main(String[] args) { Stream stream = Stream.of("GFG", "Geeks", "for", "GeeksforGeeks");
// Sort strings in reverse order, extract character at index 1, and print
stream.sorted(Comparator.reverseOrder())
.flatMap(str -> Stream.of(str.charAt(1)))
.forEach(System.out::println);
}}
`
**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.