Collection iteration refers to the process of accessing each element within a collection and performing operations on them. The Java Collections Framework provides multiple approaches for traversing collections.
Traditional Index-Based Loop
For List implementations, the classic index-based for loop remains a viable option:
List<String> items = Arrays.asList("Red", "Green", "Blue");
for (int index = 0; index < items.size(); index++) {
System.out.println(items.get(index));
}
Enhanced For-Each Loop
Since Java 5, the enhanced for-each loop offers a more readable alternative for iterating over collections:
for (String item : items) {
System.out.println(item);
}
Using Iterator
The Iterator interface provides a mechanism to traverse collections without exposing their underlying structure. Every Collection implementation supplies an iterator() method:
Iterator<String> iter = items.iterator();
while (iter.hasNext()) {
String element = iter.next();
System.out.println(element);
}
Stream API
Java 8 introduced the Stream API, enabling functional-style operations on collections:
items.stream().forEach(System.out::println);
Spliterator
Java 8 also added Spliterator, designed for traversing and partitioning collection elemants, with built-in support for parallel operations:
Spliterator<String> split = items.spliterator();
while (split.tryAdvance(element -> System.out.println(element))) {
// processing continues
}
Collection forEach Method
The Collection interface includes a forEach method that accepts a Consumer functional interface:
items.forEach(element -> System.out.println(element));
Stream peek Method
The peek method proves useful when debugging stream pipelines or performing side operations during stream processing:
List<String> filtered = items.stream()
.peek(System.out::println)
.filter(element -> element.length() > 3)
.collect(Collectors.toList());
Key Considerasions
Modifying a collection during iteration—adding or removing elements—typically triggers a ConcurrentModificationException. To modify collections safely during traversal, use Iterator's remove method or collect results into a new collection.
Performance varies by approach. For large datasets, Stream API with parallel processing may outperform traditional loops, though the difference is often negligible for smaller collections.