Iterator and ListIterator in Java
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
An iterator keeps a cursor that sits between elements. next() steps over one element and returns it.
Methods of Iterator
| Method | Description |
|---|---|
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.
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);
}
}[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().
| Method | Description |
|---|---|
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
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());
}
}[NAVIKA, SRIHITHA, ADVITHA]
ADVITHA SRIHITHA NAVIKAExplanation: 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
| Iterator | ListIterator | |
|---|---|---|
| Works with | Any collection | Lists only |
| Direction | Forward only | Forward and backward |
| Can remove | Yes | Yes |
| Can add or replace | No | Yes (add, set) |
| Knows the index | No | Yes (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
- Easy: Use an
Iteratorto remove all marks below 40 from a list of marks. - Harder: Use a
ListIteratorto double every even number in a list and insert a 0 after each odd number.
Key Takeaways
Was this tutorial helpful?