Iterating Over Collections with Enhanced For
You'll learn how to use the enhanced for loop efficiently with List, Set, and all other Collection types.
The Core Idea
Now that you understand how the enhanced for loop works internally (it calls iterator() behind the scenes), you can leverage it to iterate over any Collection implementation cleanly and efficiently. Whether you're working with an ArrayList, HashSet, LinkedList, or TreeSet, the enhanced for loop provides a uniform, readable syntax that hides the iterator mechanics while giving you safe, sequential access to every element.
Using Enhanced For with Collections
The beauty of the enhanced for loop is its consistency across collection types:
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
System.out.println(name); // Prints each name
}
The same syntax works identically with a Set:
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (Integer num : numbers) {
System.out.println(num); // Order not guaranteed with HashSet
}
Why It's Efficient
The enhanced for loop is just as efficient as manually using an iterator—it is using an iterator under the hood. There's no performance penalty, and you get cleaner, more maintainable code. You avoid the verbosity of hasNext() and next() calls while preventing common mistakes like forgetting to advance the iterator.
When to Use It
Use the enhanced for loop whenever you need to examine every element in a collection and don't need to modify the collection structure during iteration (no remove() calls). It's the go-to pattern for read-only traversal.
Key Takeaway: The enhanced for loop works uniformly across all Collection implementations, providing clean, efficient iteration syntax that's both readable and type-safe.