Iterating Collections in Java

Choose Java iteration styles, compare removal options, understand fail-fast limits, and measure ArrayList and LinkedList traversal with JMH.

published: reading time: 18 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Choose Java iteration styles, compare removal options, understand fail-fast limits, and measure ArrayList and LinkedList traversal with JMH.

Iterating Collections in Java

Java offers several ways to traverse a collection. The right choice depends on whether you need an index, removal, bidirectional movement, or a collection-specific concurrent behavior.

Introduction

When a collection changes during iteration, the right response depends on its contract. A fail-fast iterator may throw ConcurrentModificationException after an unsupported structural change, but detection is best-effort and does not make the collection thread-safe. Iterator.remove() can remove the last element returned by that iterator when removal is supported. Other collections call for removeIf, a new filtered collection, or their documented concurrent-iteration behavior.

Iteration cost also depends on the collection. ArrayList walks a backing array; LinkedList follows node references. Those layouts can matter, but the result depends on the JDK, hardware, data size, and workload. The JMH example below gives a repeatable way to measure the same traversal on both lists without assuming a fixed speed ratio.

This post covers Iterator, ListIterator, enhanced for-each, and forEach() (Java 8+). It also compares removal options and explains how iterator behavior differs across ordinary, immutable, and concurrent collections.

When to Use Each Iteration Style

Method Best For Avoid When
for loop with index Lists where you need the index or modify during iteration Any Collection without random access
Enhanced for-each Simple, read-only iteration You need direct access to the iterator
Iterator.remove() Remove the last returned element when that iterator supports removal Removal is unsupported or you need bidirectional traversal
ListIterator Bidirectional traversal and positional edits when supported General Collection (only works on List)
removeIf() Remove elements matching a predicate when the collection supports it You need a new collection and must keep the source unchanged
forEach() (Java 8+) Functional-style traversal with a non-mutating action You need iterator-based removal

The Iterator Interface

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove();  // Optional, removes last element returned by next()
    default void forEachRemaining(Consumer<? super E> action) { }
}

Fail-Fast and Concurrent Iteration

Many iterators from collections such as ArrayList are fail-fast. If the collection is structurally modified outside the iterator while traversal is in progress, an iterator may throw ConcurrentModificationException. This is best-effort bug detection, not a correctness guarantee or a concurrency mechanism. Do not use the exception to coordinate threads or to decide whether a modification happened.

Concurrent collections define their own behavior. ConcurrentHashMap iterators are weakly consistent: they may reflect updates made during iteration and do not throw ConcurrentModificationException. CopyOnWriteArrayList iterators traverse a snapshot of the array as it existed when the iterator was created. “Fail-safe” is not a general JDK iterator category, so use the specific collection’s contract.

Mermaid Diagram: Iterator and Collection Relationship

sequenceDiagram
    participant Client
    participant Iterator
    participant Collection
    Client->>Collection: iterator()
    Collection->>Iterator: create Iterator(cursor=0, lastReturned=null)
    Iterator-->>Client: Iterator instance
    loop while it.hasNext()
        Client->>Iterator: next()
        Iterator->>Collection: implementation-specific change check
        Collection-->>Iterator: may detect a change
        Iterator->>Iterator: advance cursor, update lastReturned
        Iterator-->>Client: element
    end
    alt concurrent modification detected
        Iterator->>Client: ConcurrentModificationException
    end

The diagram is illustrative. modCount checks are implementation details, and fail-fast detection is not guaranteed.

Failure Scenarios

Exception Cause Result
ConcurrentModificationException A fail-fast iterator detects an external structural change Best-effort diagnostic; not guaranteed
NoSuchElementException Calling next() when hasNext() is false No element is available
IllegalStateException Calling remove() before next() or twice Iterator state does not allow removal
IndexOutOfBoundsException ListIterator is used with an invalid index Index is outside the list
UnsupportedOperationException An optional removal operation is unsupported Removal is rejected

Trade-Off Table

Iteration Method Removal behavior Direction Iteration policy
for loop Collection-specific calls; not through an iterator Forward No iterator policy
For-each loop Iterator is hidden; use only for traversal Forward Depends on source iterator
Iterator.remove() Optional; may throw UnsupportedOperationException Forward Depends on iterator
ListIterator remove, add, and set are optional operations Both directions Depends on list implementation
removeIf() Optional collection operation Predicate-based Depends on implementation
ConcurrentHashMap iterator Supports iterator removal Forward Weakly consistent; no ConcurrentModificationException

Code Snippets

Choose a Removal Strategy

Choose a removal method that the collection supports. Iterator.remove() removes the last element returned by that iterator, but it is an optional operation and may throw UnsupportedOperationException. Collection.removeIf() is also optional. Immutable collections such as List.of(...) and fixed-size lists such as Arrays.asList(...) reject removal. If you need a filtered result without changing the source, collect matching values into a new list. Stream operations should not modify their source as part of the pipeline.

For a mutable collection whose iterator supports removal, use the iterator for per-element decisions. For predicate-based removal, removeIf() is shorter. If you need to preserve an immutable source, stream into a separate collection instead:

List<String> names = new ArrayList<>(List.of("Ada", "Bob", "Ari"));
names.removeIf(name -> name.startsWith("A"));
// names = ["Bob"]

List<String> source = List.of("Ada", "Bob", "Ari");
List<String> filtered = source.stream()
    .filter(name -> !name.startsWith("A"))
    .collect(Collectors.toCollection(ArrayList::new));
// source is unchanged; filtered = ["Bob"]

Filter a list mid-iteration by checking a condition on each element and removing it via the iterator when the condition is true. The example below drops every entry matching “b” or “c”:

List<String> list = new ArrayList<>(List.of("a", "b", "c", "d"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.equals("b") || s.equals("c")) {
        it.remove();  // Works when this iterator supports removal
    }
}
// list = ["a", "d"]

ListIterator for Bidirectional Traversal

ListIterator adds backward movement and positional edits to the basic iterator contract. Its cursor tracks two things: the element you last received from next() (or previous()) and the position right before the current element. Call next() and the cursor slides forward; call previous() and it slides back. At the current position you can call set() to replace the last returned element or add() to insert a new one before the cursor.

ListIterator provides list-specific edits during traversal without making unsupported external structural changes. Its remove(), add(), and set() operations are optional too, so check the list implementation’s contract.

List<String> list = new ArrayList<>(List.of("x", "y", "z"));
ListIterator<String> it = list.listIterator();

it.next();          // "x"
it.next();          // "y"
it.previous();      // "y"
it.set("Y");        // Replace "y" with "Y"
it.add("new");      // Insert after "Y"
// list = ["x", "Y", "new", "z"]

forEachRemaining with Lambda

forEachRemaining() is a default method on Iterator (Java 8+) that runs a Consumer against every element left in the iterator. It replaces the boilerplate while (it.hasNext()) { action(it.next()); } pattern with a single call. Once called, the iterator is exhausted — there is no resuming from where you left off.

A useful pattern is partial consumption: advance the iterator manually with a few next() calls to skip the head of a collection, then hand the remainder to forEachRemaining(). This lets you skip expensive first elements without discarding the already-obtained iterator instance.

List<Integer> nums = List.of(1, 2, 3, 4, 5);
Iterator<Integer> it = nums.iterator();
it.forEachRemaining(n -> {
    if (n % 2 == 0) System.out.println(n);  // 2, 4
});

Iterating Different Collection Types

Sets behave differently from lists during iteration. Since sets have no indexed access, your only options are the enhanced for-each loop or an explicit iterator. The more important distinction is which Set implementation determines the order:

  • HashSet gives O(1) operations but iteration order is unpredictable — it can differ from insertion order.
  • LinkedHashSet remembers insertion order, so traversal follows the order elements were added.
  • TreeSet keeps elements sorted by their natural ordering or by a supplied Comparator.

Maps expose three separate views: entrySet(), keySet(), and values(). Iterate entrySet() when you need both key and value — it avoids a per-element map lookup. keySet() is fine when you only need the keys. values() is for when the keys are irrelevant.

// Set — no guaranteed order
Set<String> set = new HashSet<>(List.of("a", "b", "c"));
for (String s : set) { System.out.println(s); }

// Map — iterate entries, keys, or values
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
for (Map.Entry<String, Integer> e : map.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}

Comparing Sequential List Traversal with JMH

ArrayList and LinkedList have different storage layouts, but a fixed speed ratio would be misleading. This JMH benchmark sums the same sequence for both lists at two dataset sizes. It sets three one-second warmup iterations, five one-second measurement iterations, and two forks. Run it on the JDK and hardware you care about, and report those details with any results.

package org.sample;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
public class CollectionIterationBenchmark {
    @Param({"1000", "100000"})
    public int size;

    private List<Integer> arrayList;
    private List<Integer> linkedList;

    @Setup(Level.Trial)
    public void setUp() {
        arrayList = new ArrayList<>(size);
        linkedList = new LinkedList<>();
        for (int i = 0; i < size; i++) {
            arrayList.add(i);
            linkedList.add(i);
        }
    }

    @Benchmark
    public long sumArrayList() {
        return sum(arrayList);
    }

    @Benchmark
    public long sumLinkedList() {
        return sum(linkedList);
    }

    private static long sum(List<Integer> values) {
        long total = 0;
        for (int value : values) {
            total += value;
        }
        return total;
    }
}

Create a standalone project with the official JMH Maven archetype, place the class at src/main/java/org/sample/CollectionIterationBenchmark.java, then build and run it:

mvn archetype:generate -DinteractiveMode=false \
  -DarchetypeGroupId=org.openjdk.jmh \
  -DarchetypeArtifactId=jmh-java-benchmark-archetype \
  -DgroupId=org.sample -DartifactId=iteration-benchmark -Dversion=1.0
cd iteration-benchmark
mvn clean verify
java -jar target/benchmarks.jar 'org.sample.CollectionIterationBenchmark'

The generated JMH harness supplies annotation processing and benchmark execution. Record the JDK and hardware with results; numbers from different setups are not directly comparable.

Observability Checklist

  • Treat ConcurrentModificationException as a bug signal; do not rely on it for correctness or thread safety
  • Profile iteration time in hot paths — especially for LinkedList where random access is O(n) per index
  • Track forEach() call patterns — functional iteration can allocate lambda objects in hot paths
  • Check for repeated .iterator() calls in loops — prefer creating the iterator once and reusing it
  • Choose a concurrent collection when threads share updates, and document whether its iterator is weakly consistent or snapshot-based

Security Notes

  • Iterator consistency depends on the collection: ConcurrentHashMap iterators are weakly consistent, while CopyOnWriteArrayList iterators use a snapshot. Neither behavior describes every concurrent collection.
  • When iterating over collections containing sensitive data, ensure the iteration does not leak elements through toString(), logging, or exception messages
  • CopyOnWriteArrayList creates a full copy on each mutation — it is safe for read-heavy workloads but expensive for write-heavy ones
  • Avoid serializing iterators — they do not carry meaningful state that survives deserialization

Common Pitfalls / Anti-Patterns

  1. Calling remove() before next(): Throws IllegalStateException — you must call next() at least once before calling remove()
  2. Using for-each for removal: The loop hides its iterator. Use iterator.remove() only when the iterator supports it; otherwise check whether removeIf() is supported or build a new collection.
  3. Modifying during forEachRemaining: The iterator contract leaves behavior unspecified if the action modifies the source, unless that iterator documents a policy. Avoid changing the source in the action.
  4. Calling removeAll() during iteration: This modifies the collection outside the active iterator. The iterator may detect it, but fail-fast detection is best-effort; choose a supported removal method instead.
  5. Assuming order in HashSet iteration: HashSet does not guarantee iteration order; use LinkedHashSet for insertion-order or TreeSet for sorted-order iteration

Quick Recap

  • Use Iterator when you need forward traversal; call remove() only if the iterator supports it
  • Use ListIterator for bidirectional traversal and list edits that the implementation supports
  • Use for-each for simple read-only loops
  • Use forEach() (Java 8+) for functional-style operations
  • Fail-fast iterators may report unsupported structural changes, but do not rely on that detection for correctness or thread safety
  • Choose among Iterator.remove(), removeIf(), a new filtered collection, or a concurrent collection based on the collection’s contract
  • Keep stream pipeline actions non-interfering; do not mutate the stream source

Interview Questions

1. What causes `ConcurrentModificationException`?
A fail-fast iterator may throw it after it detects a structural change made outside that iterator. This is best-effort bug detection: an implementation is not required to catch every such change, and the exception does not provide thread safety.
2. What is the difference between `Iterator` and `ListIterator`?
`Iterator` is unidirectional and works on any `Collection`. `ListIterator` is for `List` values and adds bidirectional traversal, index queries, and positional `add()`, `set()`, and `remove()` operations. Those mutation methods are optional and depend on the list implementation.
3. How do you safely remove elements while iterating?
Choose based on the collection. Use `Iterator.remove()` for per-element removal only when that iterator supports it; use `removeIf()` when the collection supports predicate removal. Immutable or fixed-size collections may throw `UnsupportedOperationException`. If the source must stay unchanged, create a filtered collection instead, and do not mutate a stream's source from inside its pipeline.
4. What does "fail-fast" mean in the context of Java iterators?
A fail-fast iterator may throw `ConcurrentModificationException` when it detects an unsupported structural change. Detection is best-effort and intended to expose bugs; it does not make concurrent access safe. Use a collection with a concurrency policy suited to the access pattern, and follow its iterator contract.
5. How does `forEach()` differ from enhanced for-each in Java 8+?
For an `Iterable`, enhanced for-each uses its iterator but does not expose it. `Iterable.forEach()` accepts a `Consumer` and invokes it for each element. Neither form is a general removal mechanism; behavior during concurrent changes depends on the source collection. Stream pipelines have a separate non-interference rule: do not modify their source from a pipeline action.
6. What is the difference between `Iterator` and `Iterable`?
`Iterable` provides an `iterator()` method, which lets an object work in enhanced for-each. `Iterator` traverses the elements with `hasNext()` and `next()`; its `remove()` operation is optional. Implementing `Iterable` does not require implementing `Iterator` on the collection itself.
7. How does `listIterator()` differ from `iterator()`?
`iterator()` returns a forward-only `Iterator`. `listIterator()` returns a `ListIterator` that can move in both directions and query cursor positions with `nextIndex()` and `previousIndex()`. Its `set()`, `add()`, and `remove()` operations are optional.
8. What causes `IllegalStateException` when calling `iterator.remove()`?
`IllegalStateException` is thrown when `remove()` is called before the iterator has returned an element, or when it is called twice without another traversal step. For a `ListIterator`, `previous()` also returns an element that may be removed. Removal can still throw `UnsupportedOperationException` when the operation is not supported.
9. What iteration behavior does `ConcurrentHashMap` provide?
Its iterators are weakly consistent: they may reflect updates made while iteration is in progress, do not throw `ConcurrentModificationException`, and are intended for use by one thread at a time. They are not snapshot iterators. This is a collection-specific contract, not a universal "fail-safe" category.
10. What is the difference between `toArray()` and `toArray(T[] a)`?
`toArray()` returns an `Object[]` array — the runtime type is always `Object[]`, not the actual element type. `toArray(T[] a)` populates the provided array with elements, creating a typed array. If the collection fits in the given array, it is returned; otherwise, a new array of the same runtime type is allocated."

11. When should you use `Enumeration` instead of `Iterator`?
`Enumeration` is the legacy traversal interface used by APIs such as `Vector.elements()` and `Hashtable.keys()`. `Iterator` is the usual choice for newer APIs and has an optional `remove()` operation. If an API returns an `Enumeration`, use it or convert it with `Enumeration.asIterator()`.
12. What is the purpose of the `forEachRemaining()` method in Iterator?
`forEachRemaining(action)` performs the given action on each remaining element in the iteration, then exhausts the iterator. It is more convenient than a manual while loop: `iterator.forEachRemaining(System.out::println)`. Internally, it repeatedly calls `next()` and applies the action until no elements remain."

13. How does iterator fail-fast behavior protect against concurrent modification?
It does not protect a collection from concurrent modification. Some iterators check for structural changes and may throw `ConcurrentModificationException`, but that check is best-effort and implementation-specific. Use synchronization or a concurrent collection when threads share updates.
14. What is the difference between `Iterator.remove()` and `Collection.remove()` during iteration?
`Iterator.remove()` removes the last returned element with well-defined iterator semantics when supported; the operation is optional and may throw `UnsupportedOperationException`. Calling `Collection.remove()` on the traversed source is an external structural change. A fail-fast iterator may detect it, but it is not guaranteed to throw `ConcurrentModificationException`.
15. When does `ConcurrentModificationException` not get thrown despite concurrent modification?
There is no guaranteed point at which it will be thrown. Fail-fast behavior is best-effort, so an implementation may not detect a structural change at all. Code must remain correct without relying on `ConcurrentModificationException`.
16. What is the performance characteristic of `ListIterator` compared to `Iterator`?
Both have the same O(1) per-element iteration complexity. `ListIterator` has additional overhead for maintaining bidirectional state (previous/next cursor position). For unidirectional forward iteration, `Iterator` is slightly more efficient. `ListIterator` is required only when backward traversal or positional modification is needed."

17. How does `Iterable.forEach()` method differ from the enhanced for-each loop?
`Iterable.forEach()` (Java 8+) accepts a `Consumer`; enhanced for-each uses an iterator for `Iterable` values. `forEach()` itself is sequential. `parallelStream()` is a separate operation, and its behavioral parameters should not modify the source collection.
18. What is the difference between `remove()` and `removeAll()` when called from an iterator?
`Iterator.remove()` targets the last element returned by that iterator, if removal is supported. `Collection.removeAll()` is a separate optional collection operation. Calling it on the source during an active traversal is an external structural change; a fail-fast iterator may detect it, but detection is not guaranteed. For predicate-based bulk removal, use `removeIf()` when supported.
19. How does Java's for-each loop desugar to iterator logic?
The enhanced for-each (`for (E e : collection)`) desugars to `for (Iterator i = collection.iterator(); i.hasNext(); ) { E e = i.next(); ... }`. The compiler performs this transformation automatically. For arrays, it desugars to an index-based loop instead."

20. What is the difference between Enumeration and Iterator, and when should you use each?
`Enumeration` is the older interface returned by some legacy APIs. `Iterator` uses `hasNext()` and `next()` and adds an optional `remove()` operation. Use the interface provided by the API you are calling; when needed, `Enumeration.asIterator()` adapts an enumeration.

Further Reading

Conclusion

Iteration behavior depends on the collection contract. Iterator.remove() and removeIf() are optional operations, so check whether the chosen collection supports them. If it does not, build a new filtered collection or use a collection-specific operation. Streams should not mutate their source.

Fail-fast iterators may report an external structural change with ConcurrentModificationException, but the check is best-effort. It does not provide thread safety, and code should not depend on the exception. Concurrent collections have their own iterator policies; for example, ConcurrentHashMap is weakly consistent and CopyOnWriteArrayList provides a snapshot iterator.

For a performance comparison, run the JMH benchmark with the same data and traversal on the target JDK and hardware. Report the measured result for that setup rather than assuming one list is a fixed multiple faster.

Iteration patterns apply to every collection type — HashMap, TreeMap, ArrayList, LinkedList, HashSet, TreeSet, and Queue/Deque all share the same underlying iterator contracts. Once iteration mechanics are solid, HashMap entry iteration and Queue processing patterns become straightforward to reason about.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals