Java Iterator

An Iterator in Java is an object that allows you to traverse a collection, one element at a time. It provides methods to check if there are more elements and to access and remove elements during iteration.

1. Using an Iterator

You can obtain an Iterator from any collection that implements the Iterable interface.

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            System.out.println(item);
        }
    }
}

2. Iterator Methods

  • hasNext() - Returns true if there are more elements.
  • next() - Returns the next element.
  • remove() - Removes the last element returned by next().

3. Modifying Collection During Iteration

It's safe to remove elements using the Iterator's remove() method during iteration.

while (iterator.hasNext()) {
    String item = iterator.next();
    if (item.equals("Banana")) {
        iterator.remove();
    }
}

4. For-Each Loop vs. Iterator

The for-each loop is more concise but doesn't allow modification of the collection during iteration. Use an Iterator when you need to remove elements safely.

5. Key Takeaways

  • Iterators provide a way to traverse collections safely.
  • Use iterator() method to obtain an Iterator.
  • Allows safe removal of elements during iteration.
  • Avoid modifying the collection directly while iterating; use the Iterator's methods.