Collections: ListIterator can add, set and walk backwards mid-iteration

Unlike a plain Iterator, ListIterator can replace the last-returned element with set, insert with add, and then reverse direction with previous, all during the same pass.

Code
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3));
ListIterator<Integer> it = nums.listIterator();
while (it.hasNext()) {
    int val = it.next();
    if (val == 2) {
        it.set(20);
        it.add(25);
    }
}
System.out.println("Forward pass result: " + nums);
StringBuilder back = new StringBuilder();
while (it.hasPrevious()) {
    back.append(it.previous()).append(" ");
}
System.out.println("Backward walk: " + back.toString().trim());
Output
Forward pass result: [1, 20, 25, 3]
Backward walk: 3 25 20 1
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms