Loop Through a List
Java offers half a dozen ways to visit every element of a list: the for-each loop, an index loop, an Iterator, the forEach method, streams, and loops that run backwards or count. They all reach the same elements but differ in what they let you do along the way. This page runs each style, shows the traps, and measures them on five million elements.
Contents
How each loop reaches the elements
Every loop over a list ends up in one of two mechanisms. The for-each loop, the IteratorforEachget(i)ArrayListget(i)LinkedListget(i)
The styles also differ in what they allow inside the loop: only an index loop knows the position without extra work, only an explicit iterator can remove elements safely, and only ordinary loops can break
| Style | Since | Gives you | Best for |
|---|---|---|---|
for (T x : list) | Java 5 | Each element | Most loops |
for (int i = 0; i < list.size(); i++) | Java 1.0 | Index and element | Positions, neighbours, every n-th element |
IteratorListIterator | Java 1.2 | Element, safe removeset | Changing the list while looping |
list.forEach(x -> ...) | Java 8 | Each element in a lambda | One short action per element |
list.stream()... | Java 8 | A pipeline of operations | Filtering, mapping, collecting |
for (T x : list.reversed()) | Java 21 | Elements from last to first | Backward loops |
All examples were compiled and run on JDK 21. Looping over maps is covered on
The loop styles side by side
Three tasks of a small project plan are printed with each style, so the output shows that every style visits the same elements in the same order.
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.IntStream;
public class LoopStyles {
public static void main(String[] args) {
List<String> steps = List.of("plan", "build", "test");
// 1. for-each: the default choice
for (String s : steps) {
System.out.println("for-each: " + s);
}
// 2. Index loop: when you need the position
for (int i = 0; i < steps.size(); i++) {
System.out.println("index " + i + ": " + steps.get(i));
}
// 3. forEach with a lambda or method reference
steps.forEach(s -> System.out.println("forEach: " + s));
// 4. Iterator: when you may remove while looping (see the linked page)
Iterator<String> it = steps.iterator();
while (it.hasNext()) {
System.out.println("iterator: " + it.next());
}
// 5. Backwards with a ListIterator
ListIterator<String> back = steps.listIterator(steps.size());
while (back.hasPrevious()) {
System.out.println("backwards: " + back.previous());
}
// 6. Index and value together with a stream
IntStream.range(0, steps.size())
.forEach(i -> System.out.println("step " + (i + 1) + " of " + steps.size()
+ ": " + steps.get(i)));
}
}
Output:
for-each: plan
for-each: build
for-each: test
index 0: plan
index 1: build
index 2: test
forEach: plan
forEach: build
forEach: test
iterator: plan
iterator: build
iterator: test
backwards: test
backwards: build
backwards: plan
step 1 of 3: plan
step 2 of 3: build
step 3 of 3: test
- The for-each loop is the shortest and the usual choice. It hides the iterator it uses.
- The index loop gives the position, which the "step 1 of 3" lines need.
is the stream equivalent.IntStream.range(0, size) takes a lambda and fits on one line for simple actions; with a method reference such asforEach it is shorter still.System.out::println- The explicit
loop is longer, and worth it only when you needIterator ; seeit.remove()removing while iterating . - The backward loop counts down from
. Since Java 21, looping oversize() - 1 does the same more readably.list.reversed()
Sums, early exits and LinkedList
The program computes a total with a loop and a stream, finds the first price over 40, and then runs an index loop on a LinkedList
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LoopGotchas {
public static void main(String[] args) {
// 1. A lambda cannot assign to a local variable from outside it
List<Integer> prices = List.of(30, 45, 25);
int total = 0;
for (int p : prices) { // a plain loop can update total
total += p;
}
System.out.println("total via loop: " + total);
int streamTotal = prices.stream().mapToInt(Integer::intValue).sum();
System.out.println("total via stream: " + streamTotal);
// 2. break and continue work in loops, not inside forEach
for (int p : prices) {
if (p > 40) {
System.out.println("first price over 40: " + p);
break;
}
}
// 3. get(i) on a LinkedList walks from the end each time
List<Integer> linked = new LinkedList<>();
List<Integer> array = new ArrayList<>();
for (int i = 0; i < 50000; i++) {
linked.add(i);
array.add(i);
}
System.out.println("50,000 elements, best of 3 runs:");
System.out.println(" LinkedList, index loop: "
+ best(() -> timeIndexLoop(linked)) + " ms");
System.out.println(" LinkedList, for-each: " + best(() -> timeForEach(linked)) + " ms");
System.out.println(" ArrayList, index loop: " + best(() -> timeIndexLoop(array)) + " ms");
}
static long best(java.util.function.LongSupplier run) {
long best = Long.MAX_VALUE;
for (int i = 0; i < 3; i++) {
best = Math.min(best, run.getAsLong());
}
return best;
}
static long timeIndexLoop(List<Integer> list) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
if (sum < 0) {
System.out.println(sum);
}
return (System.nanoTime() - start) / 1000000;
}
static long timeForEach(List<Integer> list) {
long start = System.nanoTime();
long sum = 0;
for (int n : list) {
sum += n;
}
if (sum < 0) {
System.out.println(sum);
}
return (System.nanoTime() - start) / 1000000;
}
}
Output (each timing is the fastest of three runs on a 2-CPU Linux machine, so read them as rough):
total via loop: 100
total via stream: 100
first price over 40: 45
50,000 elements, best of 3 runs:
LinkedList, index loop: 934 ms
LinkedList, for-each: 2 ms
ArrayList, index loop: 1 ms
- A loop that adds to a variable and
give the same total; the stream avoids the mutable variable.stream().mapToInt(...).sum() - Finding the first match is a loop with
, orbreak ; both stop at the first hit.stream().filter(...).findFirst() - The
index loop took several hundred times as long as the for-each loop over the same list, which finished in a millisecond or two, like theLinkedList index loop. With 50,000 elements, the 50,000 calls toArrayList walk about 625 million links in total, because each call starts from the nearer end. Use for-each unless you know the list is anget(i) ;ArrayListArrayList vs LinkedList explains why.
Traps inside loops
Five small mistakes that compile without warnings, each run on a list of three prices.
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.atomic.AtomicInteger;
public class LoopTraps {
public static void main(String[] args) {
List<Integer> prices = new ArrayList<>(List.of(10, 20, 30));
// 1. Assigning to the loop variable does not change the list
for (Integer p : prices) {
p = p * 2; // only the local copy changes
}
System.out.println("1. after doubling the loop variable: " + prices);
ListIterator<Integer> it = prices.listIterator();
while (it.hasNext()) {
it.set(it.next() * 2);
}
System.out.println(" with ListIterator.set: " + prices);
prices.replaceAll(p -> p / 2);
System.out.println(" with replaceAll back: " + prices);
// 2. forEach lambdas cannot assign local variables, and cannot break
AtomicInteger sum = new AtomicInteger();
prices.forEach(p -> sum.addAndGet(p));
System.out.println("2. sum via AtomicInteger in forEach: " + sum.get());
int found = -1;
for (int p : prices) {
if (p > 15) {
found = p;
break; // not possible inside forEach
}
}
System.out.println(" first > 15 with break: " + found);
// 3. 'return' inside forEach only ends that one call, like 'continue'
StringBuilder sb = new StringBuilder();
prices.forEach(p -> {
if (p == 20) {
return;
}
sb.append(p).append(' ');
});
System.out.println("3. return in forEach skips one element: " + sb.toString().strip());
// 4. Unboxing a null element in a for-each with int throws
List<Integer> withNull = new ArrayList<>(prices);
withNull.add(null);
try {
int total = 0;
for (int p : withNull) {
total += p;
}
System.out.println(total);
} catch (NullPointerException e) {
System.out.println("4. for (int p : list) with a null element: NullPointerException");
}
// 5. Java 21: reversed() view for backward loops
StringBuilder back = new StringBuilder();
for (int p : prices.reversed()) {
back.append(p).append(' ');
}
System.out.println("5. reversed(): " + back.toString().strip());
}
}
Output:
1. after doubling the loop variable: [10, 20, 30]
with ListIterator.set: [20, 40, 60]
with replaceAll back: [10, 20, 30]
2. sum via AtomicInteger in forEach: 60
first > 15 with break: 20
3. return in forEach skips one element: 10 30
4. for (int p : list) with a null element: NullPointerException
5. reversed(): 30 20 10
- The for-each variable is a copy of the reference, so assigning to it changes nothing in the list. To change elements, use
orListIterator.set , which both doubled the prices and halved them back.replaceAll - Lambdas cannot assign to local variables, so summing inside
needs a holder such asforEach ; a loop orAtomicInteger is cleaner. There is also nostream().sum() inbreak .forEach inside areturn lambda only ends the current call, so it behaves likeforEach : 20 was skipped and 30 was still processed.continue- Writing
unboxes eachfor (int p : list) , and aInteger element throwsnull .NullPointerException (Java 21) gives a reverse-order view without copying.reversed()
How fast is each style?
The program sums five million IntegerArrayListint[]
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class LoopSpeed {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
int[] array = new int[5000000];
for (int i = 0; i < array.length; i++) {
list.add(i);
array[i] = i;
}
System.out.printf("sum %,d elements%n", list.size());
time("for-each", () -> {
long s = 0;
for (int x : list) {
s += x;
}
return s;
});
time("index loop with get(i)", () -> {
long s = 0;
for (int i = 0; i < list.size(); i++) {
s += list.get(i);
}
return s;
});
time("explicit Iterator", () -> {
long s = 0;
for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
s += it.next();
}
return s;
});
time("forEach(lambda)", () -> {
long[] s = {0};
list.forEach(x -> s[0] += x);
return s[0];
});
time("stream mapToLong sum", () -> list.stream().mapToLong(Integer::longValue).sum());
time("int[] for loop", () -> {
long s = 0;
for (int x : array) {
s += x;
}
return s;
});
}
interface Sum {
long run();
}
// Best of 3 runs
static void time(String name, Sum f) {
long best = Long.MAX_VALUE;
long result = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
result = f.run();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-24s %6.2f ms (sum %d)%n", name, best / 1e6, result);
}
}
Output (rough timings on two Linux CPUs with JDK 21):
sum 5,000,000 elements
for-each 11.80 ms (sum 12499997500000)
index loop with get(i) 11.64 ms (sum 12499997500000)
explicit Iterator 11.67 ms (sum 12499997500000)
forEach(lambda) 11.46 ms (sum 12499997500000)
stream mapToLong sum 14.50 ms (sum 12499997500000)
int[] for loop 1.10 ms (sum 12499997500000)
- On an
, all five styles were within a few milliseconds of each other. After JIT compilation, the iterator, the index and the lambda all become a simple walk over the array.ArrayList - The
loop was between about three and ten times faster than any of them across runs. Each list element is a separateint[] object that must be loaded and unboxed, while the array holds the numbers directly. For large numeric data, the container matters far more than the loop style.Integer
What each loop does when the list changes
Changing a list while looping over it is the most common loop bug, and each style fails differently. Some throw ConcurrentModificationExceptionmodCountArrayList
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class LoopWhileChanging {
public static void main(String[] args) {
// 1. for-each and add: the iterator notices on the next step
List<String> tasks = new ArrayList<>(List.of("plan", "build", "test"));
try {
for (String t : tasks) {
if (t.equals("plan")) {
tasks.add("review");
}
}
} catch (ConcurrentModificationException e) {
System.out.println("for-each + add: ConcurrentModificationException, list " + tasks);
}
// 2. Removing the second-to-last element ends the loop early, with no exception
List<String> letters = new ArrayList<>(List.of("a", "b", "c"));
List<String> visited = new ArrayList<>();
for (String s : letters) {
visited.add(s);
if (s.equals("b")) {
letters.remove(s);
}
}
System.out.println("removed b in for-each: visited " + visited + ", list " + letters);
// 3. An index loop that removes skips the element that slides into place
List<Integer> nums = new ArrayList<>(List.of(2, 4, 5, 6, 8));
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) % 2 == 0) {
nums.remove(i);
}
}
System.out.println("index loop removing evens from [2, 4, 5, 6, 8]: " + nums);
// 4. An index loop that adds sees the new elements, which can loop forever
List<Integer> grow = new ArrayList<>(List.of(1, 2));
int steps = 0;
for (int i = 0; i < grow.size() && steps < 10; i++, steps++) {
grow.add(grow.get(i) * 10);
}
System.out.println("index loop adding: stopped by the cap after " + steps
+ " steps, size " + grow.size());
// 5. forEach on an ArrayList stops at the next element, then throws
List<String> names = new ArrayList<>(List.of("ann", "ben", "cy"));
List<String> seen = new ArrayList<>();
try {
names.forEach(n -> {
seen.add(n);
if (n.equals("ann")) {
names.add("dee");
}
});
} catch (ConcurrentModificationException e) {
System.out.println("forEach + add: exception after visiting "
+ seen + ", list " + names);
}
// 6. CopyOnWriteArrayList iterates a snapshot, so changes are allowed but not seen
List<String> cow = new CopyOnWriteArrayList<>(List.of("x", "y"));
List<String> cowSeen = new ArrayList<>();
for (String s : cow) {
cowSeen.add(s);
cow.add(s + "!");
}
System.out.println("CopyOnWriteArrayList: visited " + cowSeen + ", list " + cow);
}
}
for-each + add: ConcurrentModificationException, list [plan, build, test, review]
removed b in for-each: visited [a, b], list [a, c]
index loop removing evens from [2, 4, 5, 6, 8]: [4, 5, 8]
index loop adding: stopped by the cap after 10 steps, size 12
forEach + add: exception after visiting [ann], list [ann, ben, cy, dee]
CopyOnWriteArrayList: visited [x, y], list [x, y, x!, y!]
- Adding inside a for-each loop threw on the step after the add. The exception does not undo anything: the list already held
when it was caught.review - Removing
, the second-to-last element, threw nothing and the loop never visitedb . After the removal the size dropped to 2, soc returned false beforehasNext() could run its check. The bug hides in tests that happen to remove that element.next() - The index loop that removed even numbers left
. Each removal shifted the next element into the current index, and[4, 5, 8] then stepped over it. Loop backwards, or usei++ , as shown onremoveIfdeleting list elements . - An index loop that appends keeps seeing the new elements because
is read on every pass. Only the cap of 10 steps stopped it, with 12 elements in the list.size() visited onlyArrayList.forEach , then threw once the loop ended. Its loop condition checksann before every element, so it stops at once but reports the problem only after leaving the loop.modCount- A
iterator walks a snapshot of the array, so adding inside the loop was allowed. The loop visited only the originalCopyOnWriteArrayList , and the list ended with four elements.[x, y]
The rule that follows: never change a list's size inside a for-each or forEachremoveaddset
Positions, pairs of lists and order in parallel
Some loops need more than the current element: its position, the element before it, the matching element of another list, or a guarantee about order. The program covers each of these with the tool that fits.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.IntStream;
public class IndexAndOrder {
public static void main(String[] args) {
List<String> names = List.of("ann", "ben", "cy", "dee");
List<Integer> scores = List.of(81, 67, 94, 72);
// ListIterator knows its position and can move both ways
ListIterator<String> it = names.listIterator();
while (it.hasNext()) {
int index = it.nextIndex();
System.out.print(index + ":" + it.next() + " ");
}
System.out.print("| back: ");
while (it.hasPrevious()) {
System.out.print(it.previous() + " ");
}
System.out.println();
// Two lists of the same length, walked together by index
IntStream.range(0, names.size())
.filter(i -> scores.get(i) >= 75)
.forEach(i -> System.out.print(names.get(i) + "=" + scores.get(i) + " "));
System.out.println("(passed)");
// Neighbouring pairs need the index
List<Integer> temps = List.of(12, 15, 11, 18, 18);
List<Integer> changes = new ArrayList<>();
for (int i = 1; i < temps.size(); i++) {
changes.add(temps.get(i) - temps.get(i - 1));
}
System.out.println("day-to-day changes in " + temps + ": " + changes);
// A parallel forEach does not keep the order; forEachOrdered does
List<Integer> big = IntStream.rangeClosed(1, 16).boxed().toList();
List<Integer> unordered = Collections.synchronizedList(new ArrayList<>());
big.parallelStream().forEach(unordered::add);
List<Integer> ordered = Collections.synchronizedList(new ArrayList<>());
big.parallelStream().forEachOrdered(ordered::add);
System.out.println("parallel forEach: " + unordered);
System.out.println("parallel forEachOrdered: " + ordered);
}
}
0:ann 1:ben 2:cy 3:dee | back: dee cy ben ann
ann=81 cy=94 (passed)
day-to-day changes in [12, 15, 11, 18, 18]: [3, -4, 7, 0]
parallel forEach: [9, 10, 11, 12, 13, 14, 15, 16, 5, 6, 7, 8, 1, 2, 3, 4]
parallel forEachOrdered: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
reported positions 0 to 3 without a separate counter, andListIterator.nextIndex() then walked the same iterator back fromprevious() todee . This works on aann too, where an index loop would be slow.LinkedList- Java has no built-in zip for two lists.
over the shared indexes picked outIntStream.range(0, size) andann=81 , the two scores of 75 or more. Check first that both lists have the same length, or the shorter one throwscy=94 .IndexOutOfBoundsException - Comparing each temperature with the one before needs an index loop starting at 1. The four changes,
, are one fewer than the five readings.[3, -4, 7, 0] - A parallel
added the 16 numbers in blocks, starting with 9 to 16 in this run, and the order changes between runs.forEach kept 1 to 16 in order, at the cost of making the threads wait for each other.forEachOrdered
Which loop to use
| You need | Use |
|---|---|
| Each element, nothing else | for-each |
| The index or neighbouring elements | An index loop on an ArrayList |
| To stop at the first match | for-each with breakfindFirst |
| To remove elements | removeIfIteratorremove |
| To replace elements | replaceAllListIterator.set |
| A short action per element | forEach |
| To filter, transform or collect | A stream |
| Last to first | list.reversed() |
Code that may receive a LinkedList | for-each, never get(i) |
Changing every element with lambdas is covered on