Java Collection Iteration Patterns: Iterator, Enhanced For, and Lambda Streams
Iterator Fundamentals
java.util.Iterator<E> exposes three core operations:
boolean hasNext()– indicates whether another element is available.E next()– returns the current element and advances the cursor; throwsNoSuchElementExceptionwhen exhausted.void remove()– deletes the element most recently returned bynext(); throwsIllegalStateExceptionif invoked without a precedingnext()or after a priorremove().
Basic Traversal Example
import java.util.List;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
List<String> basket = List.of("Apple", "Banana", "Cherry");
Iterator<String> cursor = basket.iterator();
while (cursor.hasNext()) {
String item = cursor.next();
if ("Banana".equals(item)) {
cursor.remove(); // safe removal during iteration
}
}
System.out.println(basket); // [Apple, Cherry]
}
}
Enhanced For Loop
Introduced in Java 5, the enhanced for loop hides the iterator boilerplate behind syntactic sugar:
for (Type variable : iterable) {
// body
}
Example:
List<String) tags = List.of("java", "python", "go");
for (String tag : tags) {
System.out.println(tag.toUpperCase());
}
Limitations
- Read-only access; structural modifications trigger
ConcurrentModificationException. - No index or iterator reference available for removal or replacement.
Lambda Expressions & Streams
Java 8 introduced functional iteration via the Stream API:
List<Integer> numbers = List.of(3, 7, 1, 9, 4);
// print all
numbers.stream().forEach(n -> System.out.println(n));
// filter and print
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
Stream Pipeline Components
| Stage | Purpose | Example |
|---|---|---|
| Source | Origin of data | collection.stream() |
| Intermediate | Transform/filter elements | .filter(...), .map(...) |
| Terminal | Produce result or side effect | .forEach(...), .collect(...) |
Complex Lambda Example
record Book(String title, int year) {}
List<Book> library = List.of(
new Book("Effective Java", 2001),
new Book("Clean Code", 2008),
new Book("Java Concurrency", 2006)
);
library.stream()
.filter(b -> b.year() >= 2005)
.map(Book::title)
.sorted()
.forEach(System.out::println);
Choosing the Right Approach
| Scenario | Recommended Pattern |
|---|---|
| Simple read-only traversal | Enhanced for loop |
| Need to remove elements | Explicit Iterator with remove() |
| Complex filtering/transformation | Stream + Lambda |
| Paralel processing | parallelStream() with caution |
Safe Removal Patterns
// Iterator removal
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if (it.next().startsWith("_")) {
it.remove();
}
}
// Stream-based removal (creates new list)
List<String> cleaned = list.stream()
.filter(s -> !s.startsWith("_"))
.collect(Collectors.toList());