Iterator and ListIterator in Java

Naveen AnamaneniUpdated · 5 min read

An Iterator in Java is an object that is used to traverse a collection, one element at a time. It is also the safe way to remove elements while looping. A ListIterator is a more powerful iterator for lists: it can move forward and backward, and it can add and replace elements. In this lesson, you will learn the methods of both, with examples.

How an Iterator Moves

The cursor sits between elements; next() steps over one and returns it

An iterator keeps a cursor that sits between elements. next() steps over one element and returns it.

Methods of Iterator

MethodDescription
boolean hasNext()It returns true if there are more elements.
E next()It returns the next element and moves the cursor forward.
void remove()It removes the element returned by the last next().

Example: Removing Safely with an Iterator

Let's see an example that removes long names while looping.

SafeRemove.java▶ Try it
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class SafeRemove {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(
            List.of("Navika", "Srihitha", "Advitha"));
 
        Iterator<String> it = names.iterator();
        while (it.hasNext()) {
            String name = it.next();
            if (name.length() > 6) {
                it.remove();
            }
        }
        System.out.println(names);
    }
}
Output
[Navika]

Explanation: The loop asks hasNext() before every step, and next() returns each name in turn. "Srihitha" (8 letters) and "Advitha" (7 letters) are longer than 6, so it.remove() deletes them. Removing through the iterator is safe; removing through names.remove(...) inside the loop would usually throw ConcurrentModificationException (see "ConcurrentModificationException in Java").

Methods of ListIterator

ListIterator extends Iterator and is available from list.listIterator().

MethodDescription
boolean hasPrevious()It returns true if there is an element before the cursor.
E previous()It returns the previous element and moves the cursor backward.
int nextIndex() / int previousIndex()It returns the index of the next or previous element.
void set(E e)It replaces the element returned by the last next() or previous().
void add(E e)It inserts an element at the cursor position.

Example: Changing a List with ListIterator

ListIter.java▶ Try it
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
 
public class ListIter {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Navika", "Advitha"));
 
        ListIterator<String> li = names.listIterator();
        while (li.hasNext()) {
            String name = li.next();
            li.set(name.toUpperCase());
            if (name.equals("Navika")) {
                li.add("SRIHITHA");
            }
        }
        System.out.println(names);
 
        StringBuilder backward = new StringBuilder();
        while (li.hasPrevious()) {
            backward.append(li.previous()).append(' ');
        }
        System.out.println(backward.toString().strip());
    }
}
Output
[NAVIKA, SRIHITHA, ADVITHA]
ADVITHA SRIHITHA NAVIKA

Explanation: set replaces each name with its upper-case version. After "Navika", add inserts "SRIHITHA" at the cursor, so it lands between the first and second names. Then the second loop walks backward with previous(), printing the list in reverse order.

Iterator vs ListIterator

IteratorListIterator
Works withAny collectionLists only
DirectionForward onlyForward and backward
Can removeYesYes
Can add or replaceNoYes (add, set)
Knows the indexNoYes (nextIndex, previousIndex)

Common Mistakes

Calling remove() before next(), or twice in a row. It throws IllegalStateException.

Calling next() without checking hasNext(). At the end it throws NoSuchElementException.

Removing through the list while iterating. Use the iterator's own remove.

Interview Corner

What is the difference between Iterator and ListIterator?

Iterator can traverse any collection in the forward direction only and can remove elements. ListIterator works only with lists, can traverse forward and backward with next and previous, can add and replace elements with add and set, and can report the current index with nextIndex and previousIndex.

Practice

  1. Easy: Use an Iterator to remove all marks below 40 from a list of marks.
  2. Harder: Use a ListIterator to double every even number in a list and insert a 0 after each odd number.

Quick check: Iterator and ListIterator

4 questions
1Which method checks whether more elements remain?
2Which can move backward?
3What is the safe way to remove while looping?
4What happens if you call remove() twice in a row?

Key Takeaways

Was this tutorial helpful?

Lesson 255 of 482