Side Effects in forEach
What you'll learn: You'll understand why forEach is specifically designed for performing side effects—actions that modify something outside the stream itself.
The Purpose of forEach
While most stream operations transform or filter data, forEach exists for a different reason: to do something with each element. This "something" is called a side effect—any action that changes state outside the operation itself or interacts with the external world.
Think of forEach like a mail carrier delivering letters. The carrier doesn't transform the letters (that's map's job) or filter them (that's filter's job). Instead, they perform an action: delivering each letter to its destination, causing a real-world effect.
Common Side Effects in forEach
Printing to console:
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream().forEach(name -> System.out.println(name));
Updating external state:
List<Integer> totals = new ArrayList<>();
List<Integer> numbers = List.of(1, 2, 3);
numbers.stream().forEach(n -> totals.add(n * 2)); // Modifies external list
Performing I/O operations:
names.stream().forEach(name -> {
// Writing to file, database, or network
// These are side effects
});
Why This Matters
Unlike map or filter, which return new streams for further processing, forEach returns nothing (void). It's the end of the pipeline. Its entire purpose is to execute side effects. If you're not performing a side effect, you probably don't need forEach.
Key Takeaway: forEach is designed specifically for side effects like printing, updating external collections, or performing I/O operations—actions that affect the world outside the stream itself.