Dung (Donny) Nguyen

Senior Software Engineer

Iterator

In Java, an Iterator is an interface that provides a way to traverse or iterate over a collection of objects, such as lists, sets, or other data structures. It is part of the java.util package and allows us to access elements of a collection one by one.

Here are some key points about the Iterator interface:

Basic Methods

Usage Example

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

public class IteratorExample {
    public static void main(String[] args) {
        // Create a collection
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        // Get an Iterator
        Iterator<String> iterator = fruits.iterator();

        // Iterate over the collection
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);

            // Optional remove operation
            if (fruit.equals("Banana")) {
                iterator.remove();
            }
        }

        // After removal
        System.out.println(fruits);
    }
}

Advantages

Limitations

Enhanced for-loop (for-each)

While an Iterator is useful, Java provides an enhanced for loop (for-each loop) as a more convenient way to iterate through collections, although we can’t modify the collection during iteration with this method.

for (String fruit : fruits) {
    System.out.println(fruit);
}