Java Iterator: Safe and Standard Way to Traverse Collections


Java Iterator: Safe and Standard Way to Traverse Collections

βœ… What is an Iterator?

It's an interface in java.util.

  • Provides a way to traverse a collection one element at a time.
  • Works with all Collection types (e.g., List, Set, Queue).
  • Safe way to remove elements during iteration.
🧰 Methods of Iterator
Method Description
hasNext() Returns true if there are more elements.
next() Returns the next element in the collection.
remove() Removes the current element (optional operation).
πŸ” Basic Example

import java.util.*;

public class IteratorExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");

        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
            String lang = it.next();
            System.out.println(lang);
        }
    }
}

Output:

Java
Python
C++

πŸ—‘οΈ Removing Elements Safely

List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
list.add("Three");

Iterator<String> it = list.iterator();

while (it.hasNext()) {
    String value = it.next();
    if (value.equals("Two")) {
        it.remove(); // Safe removal during iteration
    }
}

System.out.println(list); // Output: [One, Three]

🚫 Note: Don’t use list.remove(item) inside a loop β€” it causes ConcurrentModificationException.

πŸ”„ Enhanced For-Loop vs Iterator
Feature Enhanced For-Loop Iterator
Easy to use βœ… Yes ❌ Slightly verbose
Can remove elements safely ❌ No βœ… Yes
Works with collections βœ… Yes βœ… Yes