Common Ways to Iterate
Method | When to Use |
---|---|
for-each loop | Simple read-only iteration |
Iterator | When you need to remove items safely |
ListIterator | Bi-directional iteration (only for List) |
for loop (index) | Index-based control (only for List) |
Streams / forEach() | Modern, functional style (Java 8+) |
Example
// Can't safely remove items using this method.
List<String> names = List.of("A", "B", "C");
for (String name : names) {
System.out.println(name);
}
// Avoids ConcurrentModificationException.
List<String> names = new ArrayList<>(List.of("A", "B", "C"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
if (name.equals("B")) {
it.remove(); // safe removal
}
}
// Can iterate both directions, modify in-place.
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
ListIterator<String> lit = list.listIterator();
while (lit.hasNext()) {
String val = lit.next();
if (val.equals("B")) {
lit.set("Z"); // Replaces "B" with "Z"
}
}
// Can't remove or modify elements inside forEach() directly.
list.forEach(item -> System.out.println(item));
// Occurs when a collection is modified during
// iteration using methods other than Iterator.remove().
for (String s : list) {
list.remove(s); // will throw exception
}
Best Practices
- Use Iterator.remove() when modifying during iteration.
- Use ListIterator if you need both forward and backward access.
- Avoid modifying for-each or forEach() lambda.
- Prefer modern for-each or streams when you donβt need to mutate.
Tip
Be ready to:
- safely remove elements from list during iteration,
- explain difference between Iterator and ListIterator,
- talk about ConcurrentModificationException and how to avoid it.
Parent: _Collections