Open In App

Java Iterator

Last Updated : 18 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An Iterator in Java is an interface used to traverse elements in a Collection sequentially.

  • It provides methods like hasNext(), next() and remove() to loop through collections and perform manipulation.
  • An Iterator is a part of the Java Collection Framework and we can use it with collections like ArrayList, LinkedList and other classes that implement the Collection interface.

Example: Here, we will use an Iterator to traverse and print each element in an ArrayList.

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

public class Geeks {
    public static void main(String[] args) {
      
        // Create an ArrayList and add some elements
        ArrayList<String> al = new ArrayList<>();
        al.add("A");
        al.add("B");
        al.add("C");

        // Obtain an iterator for the ArrayList
        Iterator<String> it = al.iterator();

        // Iterate through the elements and print each one
        while (it.hasNext()) {
          
            // Get the next element
            String n = it.next(); 
            System.out.println(n);      
        }
    }
}

Output
A
B
C

Cursor

A Java Cursor is an object that is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one.

Types of Cursors in Java

There are 3 cursors in Java as mentioned below:

  • Iterator: An Iterator is an object that provides a way to traverse elements of a collection sequentially without exposing its underlying implementation.
  • Enumeration: An enumeration is an older interface from Java 1.0 used for iterating over collections. It only supports forward iteration and does not allow element removal.
  • ListIterator: The ListIterator extends Iterator and allows both forward and backward traversal. It also supports element modification during iteration.

Note: Spliterator can also be considered as a cursor as it is a type of Iterator only.

In Java, a cursor is a general term for an object used to traverse a collection. Iterator is one specific interface that implements this concept in the Collections Framework.

Iterators-in-Java
Java Cursors

Syntax

To use an iterator, we have to first create it from any collection object that implements the Collection interface.

Iterator<E> itr = collection.iterator();

Here, collection is an object of any class implementing the Collection interface.

Methods of Iterator Interface

The iterator interface defines three methods as listed below:

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

public boolean hasNext();

2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more element is present.

public E next();

3. remove(): Removes the last element returned by next(). This method can be called only once per call to next().

public void remove();

Note: remove() method can throw two exceptions namely as follows:

  • UnsupportedOperationException: If the remove operation is not supported by this iterator
  • IllegalStateException: If the next method has not yet been called or the remove method has already been called after the last call to the next method.

Internal Working

In this section, we will try to understand how Java Iterator and its methods work internally. Let us take the following LinkedList object to understand this functionality.

List<String> cities = new LinkedList<>();
cities.add("G-1");
cities.add("G-2");
cities.add("G-3");
.
.
.
cities.add("G-n");

Step 1: Now, let us create an Iterator object on the List object as shown below:

Iterator<String> citiesIterator = cities.iterator();

The "citiesIteartor" iterator will look like below:

Java Iterator Step 1
Step-1

Here Iterator’s Cursor is pointing before the first element of the List.

Step 2: Now, we will run the following code snippet.

citiesIterator.hasNext();
citiesIterator.next();

Java Iterator Step 2
Step-2

When we run the above code snippet, Iterator’s Cursor points to the first element in the list as shown in the above diagram.

Step 3: Now, we will run the following code snippet.

citiesIterator.hasNext();
citiesIterator.next();

Java Iterator Step 3
Step-3


When we run the above code snippet, Iterator’s Cursor points to the second element in the list as shown in the above diagram.

Step 4: Do this process to reach the Iterator’s Cursor to the end element of the List.

Java Iterator Step n
Step-4

Step 5: After reading the final element, if we run the below code snippet, it returns a “false” value.

citiesIterator.hasNext();

Java Iterator at the end

As Iterator’s Cursor points to the after the final element of the List, hasNext() method returns a false value.

Note: After observing all these diagrams, we can say that Java Iterator supports only Forward Direction Iteration as shown in the below diagram. So it is also known as Uni-Directional Cursor. However, ListIterator is bi-directional.

Java-Ilterator-6
Java Iterator: Forward Direction

Example: Here, we will use an Iterator to traverse and remove odd elements from an ArrayList.

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

public class Geeks {

    public static void main(String[] args) {
        
        // Creating an ArrayList of Integer type
        ArrayList<Integer> al = new ArrayList<>();

        // Adding elements to the ArrayList
        for (int i = 0; i < 10; i++) {
            al.add(i);
        }

        // Printing the original list
        System.out.println("Original List: " + al);

        // Creating an Iterator for the ArrayList
        Iterator<Integer> itr = al.iterator();

        // Iterating through the list and removing odd elements
        while (itr.hasNext()) {
          
            // Getting the next element
            int i = itr.next();  
            
            System.out.print(i + " ");  

            // Removing odd elements
            if (i % 2 != 0) {
                itr.remove();
            }
        }

        System.out.println();

        // Printing the modified list after removal of odd elements
        System.out.println("Modified List: " + al);
    }
}

Output
Original List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9 
Modified List: [0, 2, 4, 6, 8]

Explanation: In the above example, we create an ArrayList of integers then iterates through it using an Iterator and removes all odd numbers. It prints the list before and after removing the odd elements and prints the modified list with only even numbers.


Iterator in Java
Visit Course explore course icon

Similar Reads