Java Iterator Interface


The Iterator Interface in Java is a part of the java.util package. It is used to iterate over the elements in a collection, such as List, Set, or Queue. Iterators provide a way to access elements in a collection without exposing the underlying data structure. This article delves into the core features, methods, and use cases of the Iterator Interface in Java.


What is the Iterator Interface?

The Iterator interface is one of the most common methods used to traverse collections in Java. It provides methods to check for the next element, get the next element, and remove elements during iteration. The interface is implemented by several classes in the Java Collections Framework, such as ArrayList, HashSet, and LinkedList.


Methods of the Iterator Interface

The Iterator interface provides three essential methods:

  1. hasNext():
    Returns true if the iteration has more elements.

  2. next():
    Returns the next element in the iteration.

  3. remove():
    Removes the last element returned by the iterator from the collection. This method is optional and may throw an exception if not supported.

Here’s a breakdown of these methods:

1. hasNext()

This method checks if there are any more elements to iterate over in the collection. If the collection still has elements left, hasNext() will return true. Otherwise, it will return false.

2. next()

The next() method retrieves the next element from the collection. Once you call next(), the iterator advances to the next element, and the current element is returned.

3. remove()

The remove() method allows you to remove the element most recently returned by the iterator. It is important to note that this method can only be called once per next() call, and it will throw an IllegalStateException if called without a valid element.


Using the Java Iterator Interface: A Practical Example

Let’s take a look at a basic example of using the Iterator interface to traverse through a List of integers.

Example 1: Iterating Through a List

import java.util.*;

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

        // Creating an iterator for the List
        Iterator<Integer> iterator = numbers.iterator();

        // Using the iterator to traverse the list
        while (iterator.hasNext()) {
            Integer number = iterator.next();
            System.out.println("Number: " + number);
        }
    }
}

Explanation:

  • In this example, we create a List of integers.
  • We then get the iterator using the iterator() method.
  • The while loop uses the hasNext() method to check if there are any remaining elements to iterate over.
  • The next() method fetches and prints each element.

Output:

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

Example 2: Removing Elements Using Iterator

Here’s how we can remove elements while iterating over a collection:

import java.util.*;

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

        // Creating an iterator for the List
        Iterator<Integer> iterator = numbers.iterator();

        // Removing elements that are greater than 20
        while (iterator.hasNext()) {
            Integer number = iterator.next();
            if (number > 20) {
                iterator.remove();
            }
        }

        // Print the remaining elements
        System.out.println("Remaining numbers: " + numbers);
    }
}

Explanation:

  • In this example, we use the remove() method of the iterator to remove numbers greater than 20.
  • The iterator will automatically update the collection, ensuring that no ConcurrentModificationException occurs.

Output:

Remaining numbers: [10, 20]

Advantages of Using the Iterator Interface

  1. Avoids ConcurrentModificationException:
    The iterator provides a safe way to remove elements while iterating over a collection. Direct modification of collections (such as removing elements from a List while iterating using a for-each loop) can lead to a ConcurrentModificationException.

  2. Flexibility:
    It can be used with any collection class that implements the Iterable interface, such as ArrayList, HashSet, and LinkedList.

  3. Encapsulation:
    The iterator pattern hides the internal workings of the collection, allowing the user to focus on traversing the elements.