Java Iterator

迭代器的使用、遍历中删除与 forEachRemaining。

Intermediate
Key PointsIterator 是遍历集合的统一方式;遍历中删除必须用 it.remove(),直接删集合会抛并发修改异常。

获取与使用迭代器

collection.iterator() returns one; hasNext() tests for more and next() advances. Calling next() when empty throws NoSuchElementException.

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

public class IteratorBasic {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("a", "b", "c"));

        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();
    }
}
Output
a b c 

遍历中删除

Calling list.remove() inside a for-each throws ConcurrentModificationException because the modification count changes. Use the iterator's own remove(), which updates that count.

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

public class IteratorRemove {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));

        Iterator<Integer> it = nums.iterator();
        while (it.hasNext()) {
            if (it.next() % 2 == 0) {
                it.remove();
            }
        }
        System.out.println(nums);

        List<Integer> nums2 = new ArrayList<>(List.of(1, 2, 3, 4, 5));
        nums2.removeIf(n -> n % 2 == 0);
        System.out.println(nums2);
    }
}
Output
[1, 3, 5]
[1, 3, 5]
Since Java 8 removeIf is usually cleaner — internally it removes safely via the iterator.

forEachRemaining

forEachRemaining(Consumer) hands the remaining elements to a function — concise with lambdas. It consumes them, so hasNext() is false afterwards.

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

public class IteratorForEach {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("x", "y"));

        Iterator<String> it = list.iterator();
        it.next();
        it.forEachRemaining(s -> System.out.println("rest: " + s));

        System.out.println(it.hasNext());
    }
}
Output
rest: y
false

Friends & Partners