Iterating Collections in Java
Choose Java iteration styles, compare removal options, understand fail-fast limits, and measure ArrayList and LinkedList traversal with JMH.
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:
HashSetgives O(1) operations but iteration order is unpredictable — it can differ from insertion order.LinkedHashSetremembers insertion order, so traversal follows the order elements were added.TreeSetkeeps elements sorted by their natural ordering or by a suppliedComparator.
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
ConcurrentModificationExceptionas a bug signal; do not rely on it for correctness or thread safety - Profile iteration time in hot paths — especially for
LinkedListwhere 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:
ConcurrentHashMapiterators are weakly consistent, whileCopyOnWriteArrayListiterators 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 CopyOnWriteArrayListcreates 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
- Calling
remove()beforenext(): ThrowsIllegalStateException— you must callnext()at least once before callingremove() - Using for-each for removal: The loop hides its iterator. Use
iterator.remove()only when the iterator supports it; otherwise check whetherremoveIf()is supported or build a new collection. - 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. - 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. - Assuming order in HashSet iteration: HashSet does not guarantee iteration order; use
LinkedHashSetfor insertion-order orTreeSetfor sorted-order iteration
Quick Recap
- Use
Iteratorwhen you need forward traversal; callremove()only if the iterator supports it - Use
ListIteratorfor bidirectional traversal and list edits that the implementation supports - Use
for-eachfor 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
Further Reading
- Java SE 27
IteratorAPI — optional removal and iterator behavior - Java SE 27
CollectionAPI —removeIf()and other optional operations - Java SE 27
ConcurrentHashMapAPI — weakly consistent iterators - Java SE 27
StreamAPI — source non-interference and stream behavior - OpenJDK JMH project — benchmark harness and setup guide
- Java SE 27
ListIteratorAPI — bidirectional iterator interface - Baeldung: Iterator vs Iterable — Understanding the difference between the two interfaces
- Java SE: For Each Loop — How the enhanced for loop works with collections
- ArrayList — common target when iterating over lists
- HashMap — iterating over map entries and keys
- Queue and Deque — iteration patterns for queues
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.
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 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.