Loading
In Java, collections like ArrayList, HashSet, and LinkedList store multiple elements. But how do we traverse (go through) these elements one by one?
We can use loops like for or while, but Java provides a special object called Iterator to make iteration safe and consistent across all collection types.

An Iterator is like a cursor that moves through a collection. It allows us to check whether more elements exist, fetch them, and even remove elements during iteration.



What is an Iterator?

An Iterator is an object provided by Java collections framework that is used to traverse through the elements of a collection one by one.
It works with all types of collections like ArrayList, HashSet, etc., and provides three main methods:

hasNext() - Checks if more elements exist.

next() - Returns the next element.

remove() - Removes the last returned element (optional operation).



Why Do We Need Iterator?

Before iterators, collections were often traversed using loops or indexes. But:

  • Not all collections have indexes (e.g., HashSet).
  • Directly modifying collections while looping can cause errors.
Iterator solves this by providing a unified and safe way to access elements, regardless of the collection type.


Syntax

Iterator<Type> it = collection.iterator( );

Type - Type of elements in the collection.

collection.iterator() - Returns the iterator for that collection.



Example: Iterating an ArrayList

import java.util.*;

public class IteratorDemo {
    public static void main(String[ ] args) {
        ArrayList<String> names = new ArrayList<>( );
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

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

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


Output

Alice
Bob
Charlie



Example: Removing Elements using Iterator

import java.util.*;

public class RemoveWithIterator {
    public static void main(String[ ] args) {
        ArrayList<Integer> numbers = new ArrayList<>( );
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        Iterator<Integer> it = numbers.iterator( );

        while (it.hasNext( )) {
            int n = it.next( );
            if (n == 20) {
                it.remove( ); // removes 20 safely
            }
        }

        System.out.println(numbers);
    }
}


Output

[10, 30]

Note: If you try to remove elements directly in a loop, you may get a ConcurrentModificationException. Iterator prevents this.



Enhanced For Loop vs Iterator

For-each loop - Simpler and shorter, but cannot remove elements during iteration.

Iterator - More powerful, allows element removal and is useful when you need more control.



Key Point

  • Iterator is part of java.util package.
  • Works with all collections (ArrayList, HashSet, LinkedList, etc.).
  • Provides hasNext( ), next( ) and remove ( ).
  • Preferred when you need to safely remove elements while looping.


Real Life Example

Imagine you have a shopping car with items like Shoes, T-shirt, Laptop. if you just want to see all items, you can use for-each loop.
But if you want to remove an item (like Shoes) while looping, for-each will give an error.

Here, Iterator is helpful because it allows safe removal of items during iteration.

Example

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

public class ShoppingCart {
    public static void main(String[ ] args) {
        List<String> cart = new ArrayList<>( );
        cart.add("Shoes");
        cart.add("T-shirt");
        cart.add("Laptop");

        Iterator<String> it = cart.iterator();
        while (it.hasNext( )) {
            String item = it.next( );
            if (item.equals("Shoes")) {
                it.remove( ); // Safe removal
            }
        }

        System.out.println(cart);
    }
}


Output

[T-shirt, Laptop]




Two Minute Drill

  • Iterator is a special object to traverse collections.
  • Methods: hasNext( ), next( ), remove( ).
  • Useful for safe iteration and removal of elements.
  • Works with all collections, unlike index-based loops.
  • Better control than enhanced for loop.