forEach vs Enhanced for Loop
What you'll learn: You'll understand the practical differences between forEach and the traditional enhanced for loop, and when to use each for iteration.
Core Differences
Both forEach (the Stream terminal operation) and the enhanced for loop let you iterate over collections, but they serve different purposes.
The enhanced for loop is a control structure that works directly with any Iterable. It's eager, imperative, and gives you full control:
List<String> names = Arrays.asList("Alice", "Bob", "Carol");
for (String name : names) {
System.out.println(name);
}
The forEach terminal operation is part of a functional pipeline. It processes elements through the Stream API:
names.stream()
.forEach(name -> System.out.println(name));
When to Use Each
Use Enhanced For Loop When:
- You need simple, direct iteration without transformations
- You want to
breakorcontinue(not possible withforEach) - You need to catch checked exceptions easily
- Performance is critical for small collections (slightly less overhead)
Use forEach When:
- You're already working with a Stream pipeline
- You want to chain with
filter,map, or other operations - You're processing parallel streams and need thread-safe iteration
Think of It This Way
The enhanced for loop is like walking through a parking lot row by row yourself. Stream forEach is like asking a valet service to check each car for you—you describe what to do, not how to walk through.
Key Takeaway: Use enhanced for loops for simple, direct iteration with control flow needs; use forEach as the final step in Stream pipelines where you're already transforming or filtering data.