bhylu.com

Advertisements

Java Traverse and Remove Deliberately

An Iterator separates traversal from a collection’s storage details. When removal during traversal is supported, use the iterator’s own operation according to its state rules.

Understand the idea

Call hasNext before next when you do not already know an element remains. After next, an iterator may support one remove operation for the returned element. Different collections provide different mutation and consistency guarantees. Fail-fast exceptions are useful diagnostics, not a reliable concurrency or correctness mechanism. Do not make program logic depend on a ConcurrentModificationException being thrown.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        List<Integer> groups = new ArrayList<>(List.of(0, 3, 0, 5));
        Iterator<Integer> iterator = groups.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() == 0) iterator.remove();
        }
        System.out.println(groups);
    }
}

Expected output

[3, 5]

The iterator visits each count and removes the zero through its own traversal state. Calling groups.remove directly inside an enhanced for loop would use a different mutation path. For a simple predicate-based removal on a suitable collection, removeIf can often state the intention more directly.

Check the official Java documentation for detailed contracts and supported options.