forEach Method vs Enhanced For Loop
What you'll learn: You'll understand when to use the forEach method introduced in Java 8 versus the traditional enhanced for loop for iterating over collections.
The Core Difference
Both the enhanced for loop and the forEach method let you iterate over collections, but they work differently under the hood. The enhanced for loop uses an Iterator to traverse elements sequentially, while forEach accepts a Consumer (a functional interface) that you provide, often as a lambda expression.
Enhanced For Loop Syntax
List<String> names = List.of("Alice", "Bob", "Carol");
for (String name : names) {
System.out.println(name);
}
This is familiar, explicit, and readable—you're controlling the loop yourself.
forEach Method Syntax
List<String> names = List.of("Alice", "Bob", "Carol");
names.forEach(name -> System.out.println(name));
Here, you pass behavior (the lambda) to the collection, and it handles iteration internally.
When to Use Which
Use the enhanced for loop when:
- You need to use
breakorcontinueto control flow - You want to access the loop variable outside the loop
- You're working with arrays or need maximum readability for beginners
Use forEach when:
- You're embracing a functional programming style
- You want to chain operations or pass existing methods as consumers
- You don't need loop control statements
Analogy
Think of the enhanced for loop as driving yourself—you control the steering (flow control). The forEach method is like taking a taxi—you tell the driver where to go (the consumer), but you don't control the route.
Key Takeaway: The enhanced for loop gives you more control with break/continue, while forEach offers a concise, functional style but sacrifices flow control. Choose based on your need for loop manipulation versus code brevity.