Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java LinkedList descendingIterator: inspect and remove from the tail

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

LinkedList.descendingIterator visits nodes from tail to head without first copying them into another collection.

The Java 8 program below compiles without external libraries; its output is checked against a real run.

Use the iterator for the edit

A retry queue holds three receipt states. The cursor reads the newest state first and removes the retry state through its own remove method. That is a cursor-local structural edit. Calling queue.remove while the cursor is active would create a different mutation path.

The fixture records the order it saw and then prints the remaining queue in its original head-to-tail order. Reverse traversal does not reverse the underlying list. For a permanent reordered list, use an explicit mutation or copy policy.

Do not use fail-fast as a lock

This iterator is still part of a mutable LinkedList. If another thread changes the queue, synchronize access or give a single worker ownership; an exception is a best-effort bug signal, not an isolation guarantee. See whole-traversal locking for the wrapper contract.

Working program

Java
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
public class RetryQueueReverseRead {
    public static void main(String[] args) {
        LinkedList<String> states = new LinkedList<>(Arrays.asList("queued", "retry", "settled"));
        StringBuilder seen = new StringBuilder();
        for (Iterator<String> cursor = states.descendingIterator(); cursor.hasNext();) {
            String state = cursor.next();
            if (seen.length() > 0) seen.append(',');
            seen.append(state);
            if (state.equals("retry")) cursor.remove();
        }
        System.out.println(seen);
        System.out.println(states);
    }
}

Output

Output
settled,retry,queued
[queued, settled]

Costs and boundaries

A full descending scan is O(n) time with O(1) cursor state, excluding the output string. Removing the current known node avoids a separate value search; it does not make arbitrary lookup constant time.

Common Mistakes

  • Do not call list.remove while expecting an existing cursor to stay valid.
  • Do not mistake reverse iteration for a reversed copy.
  • Do not use fail-fast behavior for thread coordination.

Read next

Java LinkedList: operations, internals and failure cases, Java LinkedList ListIterator: edit at a cursor without repeated searches, Java synchronizedList iteration: hold the wrapper lock.

java
linkedlist
linkedlist-reverse-traversal
Storage details