Stream.forEach()
Runs an action for every stream element (a terminal operation).
Available since: Java 8
Syntax
void forEach(Consumer<? super T> action)Parameters
| Parameter | Type | Description |
|---|---|---|
| action | Consumer<? super T> | The action for each element. |
Examples
Printing the result of a chain:
void main() {
Stream.of("apple", "kiwi", "banana")
.filter(s -> s.length() > 4)
.forEach(IO::println);
}Output:
apple
bananaNotes
It is a terminal operation: the stream cannot be used afterwards. Do not add elements to outside collections inside forEach() — gather the result with toList() or collect(). In a parallel stream the order is not guaranteed; forEachOrdered() keeps it.
See also
- Iterable — The interface of everything that a for-each loop can iterate over.
- Map.forEach() — Runs an action for every pair of a map.
- Consumer — An action that takes a value and returns nothing.
In the tutorial
- What a stream is — The Java Stream API — the source, intermediate and terminal operations, creating streams, lazy evaluation and why a stream can be used only once.