00:00

Java Stream forEach() Method

Last updated:

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

Stream.java (API)
// 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.

Usage
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() runs an action for every element and returns nothing A list of overdue orders is filtered and mapped to email addresses. forEach runs the send action once for each address. It returns void, so there is no result to collect. orders.stream() SOURCE filterisOverdue mapto email forEachsend(email) TERMINAL ACTION INTERMEDIATE Order is not guaranteed by the specification; use forEachOrdered() when it matters.
Figure 1: 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.

EveningTrains.java
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));
    }
}
Output
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.

LeaveBalances.java
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
    }
}
Output
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.

ForEachParallelOrder.java
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()));
    }
}
Output
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.

LowStockAlerts.java
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);
    }
}
Output
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; use collect() or toList() when you need data back.
  • Single use: after forEach() the stream is consumed.

6. forEach() vs Related Methods

MethodTypeOrderNotes
stream.forEach(a)Stream terminal operationNot guaranteedCan run in parallel
stream.forEachOrdered(a)Stream terminal operationEncounter orderOrdered even in parallel
collection.forEach(a)Iterable default methodIteration order of the collectionNo stream needed
map.forEach((k, v) -> ...)Map default methodMap's iteration orderGets key and value directly
for (T t : list)LoopIteration orderSupports 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()

Avoid
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:

CollectNotForEach.java
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);
    }
}
Output
[ivy, kai]

Other mistakes to avoid

  • Expecting to break out of forEach(). Use takeWhile(), anyMatch() or a loop.
  • Throwing checked exceptions from the action. A Consumer cannot; wrap them or use a loop.
  • Relying on order in parallel streams. Use forEachOrdered().

8. Summary

  • forEach() is a terminal operation that runs a Consumer on every element and returns void.
  • It does not guarantee encounter order; parallel streams call it from many threads.
  • Use it for real actions, not to build collections; use toList() or collect() for results.
  • For a plain loop over a collection, collection.forEach() needs no stream.

9. References