1. The forEach method: a final action on elements
Before diving into details, let’s recap what terminal and intermediate stream operations are.
- Intermediate operations (for example, filter, map, distinct, peek) — return a new stream and typically do nothing until a terminal operation is invoked.
- Terminal operations (for example, forEach, collect, count, anyMatch) — trigger the processing of stream elements and return a result (or return nothing, as forEach does).
After a terminal operation, the stream is considered closed, and you cannot apply other operations to it. It’s like trying to finish ice cream that’s already been eaten — it won’t work: the stream is already “used up”.
Now let’s look at two important methods for side effects: forEach and peek.
What does forEach do?
forEach is a terminal stream operation that performs the given action for each element of the stream. It’s commonly used for printing to the screen, logging, collecting statistics, and other side effects.
Method signature:
void forEach(Consumer<? super T> action)
Consumer<T> is a functional interface that accepts one argument and returns nothing (for example, System.out::println).
Example: Print all list elements
Suppose we have a list of user names:
List<String> users = List.of("Anna", "Boris", "Alex", "Alina", "Dmitry");
Printing all users with the Stream API is very simple:
users.stream().forEach(System.out::println);
Result:
Anna
Boris
Alex
Alina
Dmitry
You can also use a lambda expression:
users.stream().forEach(name -> System.out.println("User: " + name));
Result:
User: Anna
User: Boris
User: Alex
User: Alina
User: Dmitry
Important: forEach closes the stream
After calling forEach, the stream “closes”. You cannot continue the chain:
users.stream()
.filter(name -> name.startsWith("A"))
.forEach(System.out::println)
.map(String::toUpperCase); // Error! The stream is already closed.
Attempting to call something after forEach results in a compilation error: the terminal operation returns void, not a new stream.
2. The peek method: peeking without interfering
peek is an intermediate operation. It allows you to perform an action for each element at a certain processing stage without changing the element itself and without closing the stream.
Method signature:
Stream<T> peek(Consumer<? super T> action)
- peek returns a new stream in which the action action will be performed for each element.
- Typically used for debugging, logging, or monitoring the stream’s state.
Example: Logging after filtering
List<String> users = List.of("Anna", "Boris", "Alex", "Alina", "Dmitry");
List<Integer> nameLengths = users.stream()
.filter(name -> name.startsWith("A"))
.peek(name -> System.out.println("Passed the filter: " + name))
.map(String::length)
.collect(Collectors.toList());
Console output:
Passed the filter: Anna
Passed the filter: Alex
Passed the filter: Alina
Contents of nameLengths:
[4, 4, 5]
Where is peek handy?
- To debug a pipeline: see what happens at each stage.
- To gather statistics (for example, counting elements).
- To log data at intermediate stages.
Important: peek should not be used to modify stream elements. Use map for transformations. peek is to “peek”, not to “interfere”.
3. forEach vs. peek: what’s the difference?
| Method | Operation type | When applied | Can continue the chain? | Best suited for |
|---|---|---|---|---|
|
Terminal | At the very end of stream processing | No | Final actions (printing, logging, writing to DB) |
|
Intermediate | In the middle of the pipeline | Yes | Debugging, intermediate logging, counting |
Example: difference in usage
// Example with forEach
users.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println); // The stream ends here
// Example with peek
users.stream()
.filter(name -> name.startsWith("A"))
.peek(name -> System.out.println("Filter passed: " + name))
.map(String::toUpperCase)
.collect(Collectors.toList()); // You can continue the chain
Important to remember
- forEach is a point of no return: after it, nothing else can be done with the stream.
- peek does not guarantee actions will run unless a terminal operation is called. If you write only a chain of intermediate operations, nothing will happen.
4. Non-obvious points: forEach isn’t always the best choice!
Why you shouldn’t use forEach to modify collections?
Many beginners try to use forEach to modify collection elements or the collection itself (for example, removing elements). But this is bad practice: streams are not designed to modify source collections.
Example of incorrect usage:
List<String> names = new ArrayList<>(List.of("Anna", "Boris", "Alex"));
names.stream().forEach(name -> {
if (name.startsWith("A")) {
names.remove(name); // May lead to ConcurrentModificationException!
}
});
Result: a runtime error — you can’t modify the collection while iterating it via a stream (ConcurrentModificationException).
What should you use forEach for?
- Printing to the screen (for example, printing a report).
- Writing to logs.
- Calling external services (for example, sending email).
- Collecting statistics (for example, incrementing a counter).
5. Once again about peek: for debugging only!
It’s tempting to use peek to modify elements, for example, to increase a user’s age:
users.stream()
.peek(user -> user.setAge(user.getAge() + 1)) // Bad!
.collect(Collectors.toList());
Why is this bad?
- It breaks the declarative nature and purity of the Stream API.
- Such code becomes hard to maintain and test.
- Side effects in an intermediate operation can lead to subtle bugs.
It’s better to use map to transform data:
List<User> olderUsers = users.stream()
.map(user -> new User(user.getName(), user.getAge() + 1))
.collect(Collectors.toList());
Diagram: the difference between forEach and peek
users.stream()
.filter(...) // intermediate operation
.peek(...) // intermediate operation, "peek"
.map(...) // intermediate operation
.forEach(...) // terminal operation, "perform an action"
Explanation:
— Everything before forEach can be combined, reordered, and extended.
— After forEach the stream is closed.
6. Common mistakes when working with forEach and peek
Mistake #1: Using peek to modify data. peek is intended only for observation, not for modifying stream elements. Use map for transformations.
Mistake #2: Expecting peek to always run. peek runs only if a terminal operation follows (collect, forEach, count, etc.). Without a terminal operation, nothing happens.
Mistake #3: Trying to continue the stream after forEach. forEach is a terminal operation. No other stream methods can be called after it.
Mistake #4: Modifying the collection inside forEach. Changing the source collection (removing or adding elements) while iterating via forEach is a direct path to ConcurrentModificationException.
Mistake #5: Using forEach instead of collect to gather results. If you want to collect elements into a new collection, use collect(Collectors.toList()), not forEach with manual additions. This breaks declarativity and can lead to errors in multithreaded scenarios.
GO TO FULL VERSION