Java Stream forEach() Method
forEach() is a terminal operation of java.util.stream.Stream, available since Java 8, that performs an action, given as a Consumer, on every element of the stream. It returns void, so it is used for side effects such as printing, logging or sending messages, not for building results.
This tutorial covers the signature, the important rule that forEach() does not promise encounter order, how it differs from Iterable.forEach() and forEachOrdered(), and why it should not be used to fill collections.
1. Syntax and Method Signature
// java.util.stream.Stream<T> (Java 8)
void forEach(Consumer<? super T> action)
// primitive versions
void IntStream.forEach(IntConsumer action)
// not a stream method, but often confused with it: java.lang.Iterable<T> (Java 8)
default void forEach(Consumer<? super T> action)
The action is a Consumer<? super T> with the method void accept(T t). forEach() is terminal: calling it runs the whole pipeline and consumes the stream.
orders.stream()
.filter(Order::isOverdue)
.forEach(order -> reminderService.send(order.customerEmail()));
2. How forEach() Works
forEach() starts the pipeline and passes each element that reaches it to the action. On a sequential stream the JDK processes elements in encounter order in practice, but the specification explicitly says the behaviour is nondeterministic: it does not promise to respect encounter order, so that parallel streams can run actions on any thread as soon as elements are ready.
For a parallel stream, the action may be called at the same time from several threads, and in any order. Anything the action touches must therefore be thread-safe. If order matters, use forEachOrdered().
forEach() ends the pipeline with an action per element. Its result is the side effect itself; the method returns void.3. Java Examples
Example 1: Printing filtered results (Java 16+)
Print the names of the trains that depart after 18:00.
import java.util.List;
public class EveningTrains {
record Train(String name, int departureHour) { }
public static void main(String[] args) {
List<Train> trains = List.of(
new Train("Shatabdi", 6), new Train("Rajdhani", 19),
new Train("Duronto", 22), new Train("Intercity", 14));
trains.stream()
.filter(t -> t.departureHour() >= 18)
.map(Train::name)
.forEach(name -> System.out.println("Evening train: " + name));
}
}
Evening train: Rajdhani Evening train: Duronto
How it works: The pipeline filters and maps, and forEach() performs the final action. A method reference such as System.out::println works too when no extra text is needed.
Example 2: Iterating a map with forEach (Java 9+)
Print each employee's leave balance, sorted by name.
import java.util.Map;
import java.util.TreeMap;
public class LeaveBalances {
public static void main(String[] args) {
Map<String, Integer> leave = new TreeMap<>(Map.of("Sana", 12, "Amit", 4, "Kiran", 9));
leave.entrySet().stream()
.filter(e -> e.getValue() >= 5)
.forEach(e -> System.out.println(e.getKey() + " has " + e.getValue() + " days"));
leave.forEach((name, days) -> System.out.println(" " + name + "=" + days)); // Map.forEach, no stream
}
}
Kiran has 9 days Sana has 12 days Amit=4 Kiran=9 Sana=12
How it works: The stream version is useful when you filter or transform first. For a plain loop over a map, Map.forEach() takes a BiConsumer and needs no stream at all.
Example 3: Order in parallel streams
Print five numbered steps from a parallel stream with forEach() and compare it with the list order.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ForEachParallelOrder {
public static void main(String[] args) {
List<String> printed = new java.util.concurrent.CopyOnWriteArrayList<>();
IntStream.rangeClosed(1, 5)
.parallel()
.forEach(n -> printed.add("step-" + n));
System.out.println("forEach order: " + printed);
System.out.println("Sorted: " + printed.stream().sorted().collect(Collectors.toList()));
}
}
forEach order: [step-3, step-5, step-1, step-4, step-2] Sorted: [step-1, step-2, step-3, step-4, step-5]
The first line varies from run to run; it is one real run on a multi-core machine. The second line is always sorted.
How it works: The steps arrive in whatever order the worker threads finish. CopyOnWriteArrayList is used because the action runs on several threads; a plain ArrayList could lose elements.
Example 4: Sending notifications for each match (Java 16+)
Send a low-stock alert for every product below its reorder level. The sender is a simple method that stands in for an email or chat client.
import java.util.List;
public class LowStockAlerts {
record Product(String sku, int stock, int reorderLevel) { }
static void sendAlert(Product p) {
System.out.println("ALERT " + p.sku() + ": stock " + p.stock() + " below " + p.reorderLevel());
}
public static void main(String[] args) {
List<Product> products = List.of(
new Product("SKU-11", 4, 10), new Product("SKU-12", 40, 10),
new Product("SKU-13", 0, 5), new Product("SKU-14", 9, 8));
products.stream()
.filter(p -> p.stock() < p.reorderLevel())
.forEach(LowStockAlerts::sendAlert);
}
}
ALERT SKU-11: stock 4 below 10 ALERT SKU-13: stock 0 below 5
How it works: This is the job forEach() is for: a real action per element, at the end of the pipeline. The action is a method reference to a named method, which keeps the pipeline short.
4. Real-World Use Cases
- Notifications: send an email, SMS or webhook for each matching customer or order.
- Logging and printing: write report lines or audit entries.
- Calling external systems: publish each event to a message broker.
5. Important Points
- Order is not guaranteed by the specification, even though sequential streams follow it in practice.
- Thread safety: in parallel streams the action runs concurrently.
- Exceptions thrown by the action stop the pipeline; elements after the failure are not processed.
- Empty streams: the action is simply never called.
- No result: it returns
void; usecollect()ortoList()when you need data back. - Single use: after
forEach()the stream is consumed.
6. forEach() vs Related Methods
| Method | Type | Order | Notes |
|---|---|---|---|
stream.forEach(a) | Stream terminal operation | Not guaranteed | Can run in parallel |
stream.forEachOrdered(a) | Stream terminal operation | Encounter order | Ordered even in parallel |
collection.forEach(a) | Iterable default method | Iteration order of the collection | No stream needed |
map.forEach((k, v) -> ...) | Map default method | Map's iteration order | Gets key and value directly |
for (T t : list) | Loop | Iteration order | Supports break and checked exceptions |
If you only need to loop over a collection, collection.forEach() or a for-each loop is simpler than stream().forEach().
7. Common Mistakes and Best Practices
Building a collection with forEach()
List<String> names = new ArrayList<>();
users.stream().filter(User::isActive).forEach(u -> names.add(u.name())); // side effect
Let the stream build the result. It is shorter and stays correct in parallel:
import java.util.List;
public class CollectNotForEach {
record User(String name, boolean active) { }
public static void main(String[] args) {
List<User> users = List.of(new User("ivy", true), new User("joe", false), new User("kai", true));
List<String> names = users.stream()
.filter(User::active)
.map(User::name)
.toList();
System.out.println(names);
}
}
[ivy, kai]
Other mistakes to avoid
- Expecting to
breakout offorEach(). UsetakeWhile(),anyMatch()or a loop. - Throwing checked exceptions from the action. A
Consumercannot; wrap them or use a loop. - Relying on order in parallel streams. Use
forEachOrdered().
8. Summary
forEach()is a terminal operation that runs aConsumeron every element and returnsvoid.- It does not guarantee encounter order; parallel streams call it from many threads.
- Use it for real actions, not to build collections; use
toList()orcollect()for results. - For a plain loop over a collection,
collection.forEach()needs no stream.
9. References
Frequently Asked Questions (FAQ)
Q1. What does forEach() do in Java streams?
forEach() is a terminal operation that runs a Consumer action on every element of the stream and returns void. It triggers the pipeline and consumes the stream.
Q2. Does stream forEach() keep the order of elements?
The specification does not guarantee it. Sequential streams follow encounter order in practice, but parallel streams run the action in any order. Use forEachOrdered() when order matters.
Q3. What is the difference between stream().forEach() and Iterable.forEach()?
Iterable.forEach() is a default method on collections that loops in the collection's iteration order without creating a stream. stream().forEach() is a terminal stream operation, useful after filter() or map(), and can run in parallel.
Q4. Can I break out of a stream forEach()?
No. There is no break. Use a short-circuiting operation such as takeWhile(), anyMatch() or findFirst(), or use a regular for loop.
Q5. Should I use forEach() to add elements to a list?
No. Adding to an outside list is a side effect that breaks in parallel streams. Use toList() or collect() to build the list instead.