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 Iterator, forEach and streams all ask the list for an iterator, an object that walks from one element to the next. An index loop calls get(i) for each position instead. For an ArrayList both are fast, because get(i) reads an array slot. For a LinkedList, get(i) walks the chain from one end every time, so an index loop becomes quadratic.

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 out early or throw checked exceptions.

Ways to loop through a list
StyleSinceGives youBest for
for (T x : list)Java 5Each elementMost loops
for (int i = 0; i < list.size(); i++)Java 1.0Index and elementPositions, neighbours, every n-th element
Iterator / ListIteratorJava 1.2Element, safe remove and setChanging the list while looping
list.forEach(x -> ...)Java 8Each element in a lambdaOne short action per element
list.stream()...Java 8A pipeline of operationsFiltering, mapping, collecting
for (T x : list.reversed())Java 21Elements from last to firstBackward loops

All examples were compiled and run on JDK 21. Looping over maps is covered on looping through a map.

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.

Java
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:

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. IntStream.range(0, size) is the stream equivalent.
  • forEach takes a lambda and fits on one line for simple actions; with a method reference such as System.out::println it is shorter still.
  • The explicit Iterator loop is longer, and worth it only when you need it.remove(); see removing while iterating.
  • The backward loop counts down from size() - 1. Since Java 21, looping over list.reversed() does the same more readably.

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, the one combination that is badly slow.

Java
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):

Output
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 stream().mapToInt(...).sum() give the same total; the stream avoids the mutable variable.
  • Finding the first match is a loop with break, or stream().filter(...).findFirst(); both stop at the first hit.
  • The LinkedList 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 the ArrayList index loop. With 50,000 elements, the 50,000 calls to get(i) walk about 625 million links in total, because each call starts from the nearer end. Use for-each unless you know the list is an ArrayList; ArrayList vs LinkedList explains why.

Traps inside loops

Five small mistakes that compile without warnings, each run on a list of three prices.

Java
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:

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
  1. The for-each variable is a copy of the reference, so assigning to it changes nothing in the list. To change elements, use ListIterator.set or replaceAll, which both doubled the prices and halved them back.
  2. Lambdas cannot assign to local variables, so summing inside forEach needs a holder such as AtomicInteger; a loop or stream().sum() is cleaner. There is also no break in forEach.
  3. return inside a forEach lambda only ends the current call, so it behaves like continue: 20 was skipped and 30 was still processed.
  4. Writing for (int p : list) unboxes each Integer, and a null element throws NullPointerException.
  5. reversed() (Java 21) gives a reverse-order view without copying.

How fast is each style?

The program sums five million Integers in an ArrayList with each style, and the same numbers in an int[] for comparison, keeping the fastest of three runs.

Java
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):

Output
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 ArrayList, 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.
  • The int[] loop was between about three and ten times faster than any of them across runs. Each list element is a separate Integer 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.

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 ConcurrentModificationException, some skip elements silently, and one can run forever. The checks rely on a counter, modCount, that every structural change to an ArrayList increments; an iterator remembers the value it started with and compares on each step.

Java
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);
    }
}
Output
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 review when it was caught.
  • Removing b, the second-to-last element, threw nothing and the loop never visited c. After the removal the size dropped to 2, so hasNext() returned false before next() could run its check. The bug hides in tests that happen to remove that element.
  • The index loop that removed even numbers left [4, 5, 8]. Each removal shifted the next element into the current index, and i++ then stepped over it. Loop backwards, or use removeIf, as shown on deleting list elements.
  • An index loop that appends keeps seeing the new elements because size() is read on every pass. Only the cap of 10 steps stopped it, with 12 elements in the list.
  • ArrayList.forEach visited only ann, then threw once the loop ended. Its loop condition checks modCount before every element, so it stops at once but reports the problem only after leaving the loop.
  • A CopyOnWriteArrayList iterator walks a snapshot of the array, so adding inside the loop was allowed. The loop visited only the original [x, y], and the list ended with four elements.

The rule that follows: never change a list's size inside a for-each or forEach loop. Collect the changes and apply them after the loop, or use an iterator's own remove, add and set.

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.

Java
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);
    }
}
Output
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]
  • ListIterator.nextIndex() reported positions 0 to 3 without a separate counter, and previous() then walked the same iterator back from dee to ann. This works on a LinkedList too, where an index loop would be slow.
  • Java has no built-in zip for two lists. IntStream.range(0, size) over the shared indexes picked out ann=81 and cy=94, the two scores of 75 or more. Check first that both lists have the same length, or the shorter one throws IndexOutOfBoundsException.
  • Comparing each temperature with the one before needs an index loop starting at 1. The four changes, [3, -4, 7, 0], are one fewer than the five readings.
  • A parallel forEach added the 16 numbers in blocks, starting with 9 to 16 in this run, and the order changes between runs. forEachOrdered kept 1 to 16 in order, at the cost of making the threads wait for each other.

Which loop to use

Choosing a loop
You needUse
Each element, nothing elsefor-each
The index or neighbouring elementsAn index loop on an ArrayList
To stop at the first matchfor-each with break, or findFirst
To remove elementsremoveIf, or an Iterator with remove
To replace elementsreplaceAll or ListIterator.set
A short action per elementforEach
To filter, transform or collectA stream
Last to firstlist.reversed() (Java 21) or a counting-down index loop
Code that may receive a LinkedListfor-each, never get(i)

Changing every element with lambdas is covered on changing list items with lambdas.