0
0
JavaHow-ToBeginner · 3 min read

How to Use Stream forEach in Java: Simple Guide

In Java, you use stream().forEach() to perform an action on each element of a collection in a simple and readable way. It takes a lambda expression or method reference to define what to do with each element.
📐

Syntax

The forEach method is called on a Stream object and takes a Consumer functional interface as an argument. This defines the action to perform on each element.

  • collection.stream(): Converts the collection to a stream.
  • forEach(action): Applies the action to each element.
  • action: A lambda expression or method reference specifying what to do.
java
collection.stream().forEach(element -> {
    // action on element
});
💻

Example

This example shows how to print each name in a list using stream().forEach(). It demonstrates how to use a lambda expression to define the action.

java
import java.util.List;

public class StreamForEachExample {
    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Charlie");
        names.stream().forEach(name -> System.out.println(name));
    }
}
Output
Alice Bob Charlie
⚠️

Common Pitfalls

One common mistake is trying to modify the source collection inside forEach, which can cause errors or unexpected behavior. Also, forEach does not guarantee order unless the stream is ordered.

Another pitfall is confusing forEach with map or other stream operations that transform data. forEach is for side effects like printing or updating external state.

java
import java.util.ArrayList;
import java.util.List;

public class ForEachPitfall {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("a", "b", "c"));

        // Wrong: modifying list inside forEach (can cause ConcurrentModificationException)
        // list.stream().forEach(item -> list.remove(item));

        // Right: collect items to remove first, then remove after forEach
        List<String> toRemove = new ArrayList<>();
        list.stream().forEach(item -> {
            if (item.equals("b")) {
                toRemove.add(item);
            }
        });
        list.removeAll(toRemove);
        System.out.println(list);
    }
}
Output
[a, c]
📊

Quick Reference

  • Use: collection.stream().forEach(action) to perform an action on each element.
  • Action: A lambda like e -> doSomething(e) or method reference System.out::println.
  • Order: Preserved only if stream is ordered (e.g., from a List).
  • Side Effects: Use for side effects, not for transforming data.

Key Takeaways

Use stream().forEach() to apply an action to each element in a collection.
Pass a lambda expression or method reference to define the action inside forEach.
Avoid modifying the source collection inside forEach to prevent errors.
forEach is for side effects; use map or other methods for data transformation.
Order of processing is guaranteed only for ordered streams like those from Lists.