Java Lesson 36 – Iterators | Dataplexa

Iterators

An Iterator is a special object in Java that allows you to traverse (move through) elements of a collection safely and systematically.

Instead of accessing elements using indexes, Iterators provide a controlled way to read and remove elements from collections like ArrayList, LinkedList, and HashSet.


Why Iterators Are Needed

Using loops like for or for-each works fine for reading data, but they can cause problems when modifying a collection during iteration.

Iterators solve this problem by providing a safe mechanism to traverse and modify collections without runtime errors.


Iterator Interface

The Iterator interface belongs to the java.util package and provides three main methods:

  • hasNext() – checks if more elements exist
  • next() – returns the next element
  • remove() – removes the current element safely

Basic Iterator Example

Let us iterate through a list of names using an Iterator.


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

public class Main {
    public static void main(String[] args) {

        List names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        Iterator it = names.iterator();

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

Removing Elements Safely

One major advantage of Iterators is the ability to remove elements while iterating without causing errors.


Iterator it = names.iterator();

while (it.hasNext()) {
    String name = it.next();

    if (name.equals("Bob")) {
        it.remove();
    }
}

System.out.println(names);

Using remove() directly on the collection inside a loop would cause a runtime exception.


Iterator vs For-Each Loop

  • For-each – simple and readable for reading data
  • Iterator – required when modifying a collection

If your logic involves deleting or filtering elements, Iterator is the correct choice.


Iterating Over a HashMap

Iterators are commonly used with maps using entry sets.


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {
    public static void main(String[] args) {

        Map users = new HashMap<>();
        users.put(1, "Admin");
        users.put(2, "Editor");
        users.put(3, "Viewer");

        Iterator> it =
                users.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry entry = it.next();
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Real-World Example

Imagine filtering inactive users from a list in an application.


List users = new ArrayList<>();
users.add("ActiveUser");
users.add("InactiveUser");
users.add("ActiveAdmin");

Iterator it = users.iterator();

while (it.hasNext()) {
    if (it.next().startsWith("Inactive")) {
        it.remove();
    }
}

System.out.println(users);

This approach keeps the code safe and stable.


Common Mistakes

  • Modifying a collection inside a for-each loop
  • Calling next() without checking hasNext()
  • Using collection’s remove() instead of iterator’s remove()

Key Takeaways

  • Iterators provide safe traversal of collections
  • They allow controlled removal of elements
  • Essential for real-world collection filtering
  • Widely used in backend and enterprise Java code

In the next lesson, we will learn about Generics and how Java achieves type safety.