✅ 1. Enhanced for loop (for-each loop)
List<String> list = List.of("apple", "banana", "cherry");
for (String item : list) {
System.out.println(item);
}
Clean and readable
Can’t modify the list (no remove() here)
✅ 2. Classic for loop (index-based)
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Good when you need the index
Allows read and write access (list.set(i, newValue))
✅ 3. Iterator
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next();
System.out.println(item);
}
Use it.remove() to safely remove items during iteration
✅ 4. ListIterator (bi-directional iterator)
ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
System.out.println(it.next());
}
while (it.hasPrevious()) {
System.out.println(it.previous());
}
Can go forward and backward
Can modify the list (add(), set(), remove())
✅ 5. Java 8+ forEach() with lambda
list.forEach(item -> System.out.println(item));
Clean, functional
Read-only (can’t modify structure during iteration)
✅ 6. Stream API
list.stream()
.filter(item -> item.startsWith("a"))
.forEach(System.out::println);
✅ 7. Using a forEachRemaining() from Iterator (Java 8+)
Iterator<String> it = list.iterator();
it.forEachRemaining(item -> System.out.println(item));
Less common, but neat for one-liners with iterators
🧠 TL;DR
| Method | Use case |
|---|---|
| Enhanced for loop | Simple read-only iteration |
| Classic for loop | When you need indexes |
| Iterator | When you may remove items while iterating |
| ListIterator | Bi-directional or advanced list edits |
forEach() | Clean, lambda-based read access |
| Stream API | Filtering, transforming, chaining |