Java ProgramsCollectionsListIterator Example

ListIterator Example in Java

intermediate·  Collections  ·  Iterator

Problem

ListIterator extends the plain Iterator with the ability to move backward as well as forward, and to replace the current element in place — capabilities a plain Iterator doesn't offer at all.

Given a list of colors, walk forward replacing one element, then walk the same iterator backward to confirm the change.

Input
[Red, Green, Blue], replace Green with Yellow while moving forward
Output
Forward pass result: [Red, Yellow, Blue] Backward: Blue Yellow Red

Java Program

Java
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class ListIteratorDemo { public static void main(String[] args) { List<String> colors = new ArrayList<>(); colors.add("Red"); colors.add("Green"); colors.add("Blue"); ListIterator<String> it = colors.listIterator(); while (it.hasNext()) { String color = it.next(); if (color.equals("Green")) { it.set("Yellow"); // replaces the just-returned element in place } } System.out.println("Forward pass result: " + colors); StringBuilder reversed = new StringBuilder(); while (it.hasPrevious()) { reversed.append(it.previous()).append(" "); } System.out.println("Backward: " + reversed.toString().trim()); } }

Output

Forward pass result: [Red, Yellow, Blue] Backward: Blue Yellow Red

Core Logic

Walking forward with next() to find and replace one element with set(), then reusing the same iterator's hasPrevious()/previous() to walk back over the now-updated list, shows both directions working through one shared cursor.

How It Works
  1. 1colors.listIterator() returns a ListIterator<String>, positioned before the first element, same starting point as a plain Iterator.
  2. 2it.next() advances forward and returns each element in turn — when it returns "Green", it.set("Yellow") replaces that element in the list without needing an index.
  3. 3Once hasNext() is false, the cursor sits after the last element — hasPrevious() is now true, so the same iterator can walk backward from there.
  4. 4it.previous() moves backward one step at a time, returning each element in reverse order, starting from the last one.
The forward pass replaces Green with Yellow, leaving [Red, Yellow, Blue]; the backward pass over that same updated list then visits Blue, Yellow, Red, in that order.
💡

Key Point: A plain Iterator only ever moves forward and can only remove — set() and previous() are exactly what ListIterator adds on top of it, and both only work on List implementations, not every Collection.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Each element is visited once moving forward and once moving backward, and next()/previous()/set() are all O(1) on an ArrayList since they only read or overwrite a single array slot — unlike remove(), which needs to shift elements.

Key Concepts

ListIteratorhasPrevious()previous()set()

Related Programs