Skip to content

The Iterator Interface

An Iterator in Java is an object that allows you to traverse through a collection (such as a list, set, or any other collection) and access each element sequentially. It provides a standardized way to iterate over a collection, which is independent of the underlying structure of the collection. Iterators are part of the Java Collections Framework and can be used with List, Set, and other collections that implement the Collection interface.


Key Methods of the Iterator Interface

The Iterator interface is defined in java.util package and provides the following key methods:

  1. hasNext():
    This method checks whether there are more elements to iterate over.

    java
    boolean hasNext();
    • Returns: true if the iteration has more elements; otherwise, false.
  2. next():
    This method returns the next element in the iteration and advances the iterator.

    java
    E next();
    • Returns: The next element in the iteration.
  3. remove():
    This method removes the last element returned by the iterator. It can be used to remove elements from a collection while iterating over it.

    java
    void remove();
    • Note: The remove() method is optional in some implementations, but if supported, it removes the last element returned by the iterator.

Using Iterators in Java

Here’s an example that demonstrates how to use an iterator to iterate over a collection.

Example 1: Using an Iterator with a List

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

public class IteratorExample {
    public static void main(String[] args) {
        // Create a List of integers
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        
        // Get an Iterator for the list
        Iterator<Integer> iterator = numbers.iterator();
        
        // Iterate over the collection using the iterator
        while (iterator.hasNext()) {
            Integer number = iterator.next();
            System.out.println("Number: " + number);
        }
    }
}

Explanation:

  • We create an ArrayList of integers and add some elements to it.
  • We get an Iterator for the List by calling the iterator() method.
  • We use the hasNext() method to check if there are more elements to iterate over.
  • We use next() to get the next element in the collection and print it.

Output:

Number: 10
Number: 20
Number: 30
Number: 40

Example 2: Using remove() Method with an Iterator

You can also use the remove() method to remove elements while iterating. This is particularly useful when you want to modify the collection during iteration.

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

public class IteratorRemoveExample {
    public static void main(String[] args) {
        // Create a List of integers
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        
        // Get an Iterator for the list
        Iterator<Integer> iterator = numbers.iterator();
        
        // Iterate over the collection and remove numbers greater than 20
        while (iterator.hasNext()) {
            Integer number = iterator.next();
            if (number > 20) {
                iterator.remove();  // Remove the element if it's greater than 20
            }
        }
        
        // Print the modified list
        System.out.println("Modified List: " + numbers);
    }
}

Explanation:

  • We create a list of numbers.
  • We iterate over the list using the iterator, and if the current element is greater than 20, we remove it using the remove() method.
  • After the iteration is complete, the list will only contain elements that are less than or equal to 20.

Output:

Modified List: [10, 20]

Using Iterators with Other Collections

You can use iterators with other collections like Set and Map. Below are examples of iterating through a Set and a Map.

Example 3: Using Iterator with a Set

A Set is a collection that does not allow duplicate elements.

java
import java.util.HashSet;
import java.util.Iterator;

public class SetIteratorExample {
    public static void main(String[] args) {
        // Create a HashSet of integers
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        
        // Get an Iterator for the set
        Iterator<Integer> iterator = numbers.iterator();
        
        // Iterate over the collection using the iterator
        while (iterator.hasNext()) {
            Integer number = iterator.next();
            System.out.println("Number: " + number);
        }
    }
}

Explanation:

  • We use a HashSet to store integers.
  • We use the iterator to traverse through the set and print each element. Since sets do not guarantee any particular order, the output may vary each time.

Output (may vary due to no specific order in HashSet):

Number: 10
Number: 20
Number: 30
Number: 40

Example 4: Using Iterator with a Map

A Map stores key-value pairs. You can use iterators to iterate through the keys, values, or entries of a Map.

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

public class MapIteratorExample {
    public static void main(String[] args) {
        // Create a HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("Alice", 30);
        map.put("Bob", 25);
        map.put("Charlie", 35);

        // Get an iterator for the entry set
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();

        // Iterate over the map's entries
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Explanation:

  • We create a HashMap with String keys and Integer values.
  • We use entrySet().iterator() to get an iterator for the key-value pairs.
  • We use the next() method to retrieve each entry, and then print the key and value.

Output:

Alice: 30
Bob: 25
Charlie: 35

Iterator vs ListIterator

While the Iterator interface can be used to traverse through all types of collections (like List, Set, etc.), the ListIterator interface extends Iterator and is specifically designed for List collections. It provides additional functionality, such as:

  • Bidirectional Traversal: You can iterate both forward and backward.
  • Modify the Collection: It provides additional methods like add() and set() to modify the list during iteration.

Example of ListIterator:

java
import java.util.ArrayList;
import java.util.ListIterator;

public class ListIteratorExample {
    public static void main(String[] args) {
        // Create a List of integers
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);

        // Get a ListIterator for the list
        ListIterator<Integer> listIterator = numbers.listIterator();

        // Iterate forward
        System.out.println("Forward Iteration:");
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }

        // Iterate backward
        System.out.println("Backward Iteration:");
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
    }
}

Output:

Forward Iteration:
10
20
30
40
Backward Iteration:
40
30
20
10

Conclusion

  • Iterators in Java provide a way to traverse collections in a standardized manner.
  • They are widely used with collections such as List, Set, and Map for accessing elements sequentially.
  • The main iterator methods are hasNext(), next(), and remove().
  • ListIterator is a more advanced iterator used with lists, allowing bidirectional iteration and modification of the list during iteration.

Using iterators is an important concept in Java, especially for manipulating collections efficiently and safely.

J2J Institute private limited