Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Compare Iterable.forEach with an enhanced for loop, and explain why ArrayList.removeIf is better than removing in a loop.

Iterable.forEach(action) runs a lambda for each element, so inside it we cannot break out early, cannot assign to local variables of the enclosing method, and cannot easily throw checked exceptions; ArrayList's version also checks modCount and throws ConcurrentModificationException if the list changed during the loop. removeIf is better than removing in a loop because ArrayList.removeIf marks the elements to remove and compacts the array in one O(n) pass, while repeated remove calls shift the tail each time and cost O(n squared).

Why this question is asked

Since Java 8 we have two ways to write almost every loop over a collection, and code reviews regularly debate which one to use. The real differences are not about style: they are about control flow, exceptions, what the collection can do when it runs the loop itself, and performance when we remove elements. Interviewers ask this to see whether we know those differences beyond personal taste. In this answer, we will compare forEach with the enhanced for loop, see how ArrayList.forEach detects modification, measure why removeIf beats a removal loop, and look at the bulk methods on Map and on synchronized collections.

1Two Ways to Loop

The enhanced for loop is external iteration: our code asks the collection's Iterator for each element and runs the body itself. Iterable.forEach(Consumer) is internal iteration: we hand the collection a function, a Consumer that takes one element, and the collection decides how to walk its elements and calls our function for each one.

For a simple loop the two look and behave the same.

Java
List<String> names = List.of("ann", "bob", "carl");
for (String n : names) System.out.println(n); // ann, bob, carl
names.forEach(n -> System.out.println(n)); // ann, bob, carl
names.forEach(System.out::println); // same, with a method reference

2What We Give Up Inside a Lambda

The differences appear as soon as the body does more than print. A lambda is a separate function, so the statements break and continue have no loop to act on, return only leaves the lambda for the current element, and local variables of the enclosing method can only be read if they are effectively final.

Java
int count = 0;
for (String n : names) {
if (n.startsWith("b")) break; // fine: stops the loop
count++; // fine: count is 1 at the end
}
int total = 0;
names.forEach(n -> {
// break; // does not compile: break outside a loop
// total++; // does not compile: total must be effectively final
if (n.startsWith("b")) return; // only skips this element, like continue
});
names.forEach(n -> Files.writeString(Path.of(n), n));
// does not compile: unhandled IOException, Consumer.accept declares no checked exceptions
forEach versus the enhanced for loop
NeedEnhanced forforEach(lambda)
Stop earlybreakNot possible; use a stream's takeWhile or anyMatch
Update a local variableYesOnly effectively final locals can be read
Checked exceptionsPropagate normallyMust be caught inside the lambda
Collection controls traversalNoYes: may lock, optimise, check once

The checked exception problem is the most annoying in practice. Consumer.accept() does not declare any checked exceptions, so a lambda calling a method that throws IOException must catch it inside the lambda, often wrapping it in UncheckedIOException. With the for loop, the exception simply propagates. So the rule of thumb is: use forEach for short side effects such as logging or adding to another collection, and the for loop when we need early exit, counters or checked exceptions. If we want early exit in a functional style, streams have anyMatch, findFirst and takeWhile.

3How ArrayList.forEach Detects Modification

Because the collection runs the loop, it can implement it in the most efficient way. ArrayList.forEach loops directly over its internal array, without creating an Iterator, and instead of checking modCount on every element through next(), it saves the value at the start, stops looping as soon as the count changes, and throws ConcurrentModificationException after the loop.

Java
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.forEach(s -> {
if (s.equals("a")) list.add("z"); // changes modCount
});
// the loop stops and then throws ConcurrentModificationException

Notice that this check is more reliable than the iterator's in one respect: the second-to-last element trick, where removing an element ends a for-each loop quietly and skips the last element, does not slip through, because forEach checks the count after the loop no matter how it ended.

4Why removeIf Is Better Than Removing in a Loop

Removing from an ArrayList at index i shifts every element after i one place to the left, which is a call to System.arraycopy of size - i - 1 elements. A loop that removes k elements one by one, whether with an Iterator or by index, pays that shift k times. When half of a 100,000-element list matches, that is roughly 50,000 shifts of up to 100,000 elements each: billions of element moves, O(n squared).

Java
List<Integer> nums = new ArrayList<>();
for (int i = 0; i < 100_000; i++) nums.add(i);
// one by one: about 2.5 billion element moves
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) if (it.next() % 2 == 0) it.remove();
// removeIf: one pass, each survivor moved at most once
nums.removeIf(n -> n % 2 == 0); // about 100,000 steps

ArrayList.removeIf works in two phases. First it walks the array and records which indexes match in a compact bit set, testing each element once. Then it walks again and copies each surviving element down to its final place, and clears the leftover slots at the end. Each element is examined once and moved at most once, so the whole operation is O(n). It also checks modCount, so a predicate that modifies the list fails with ConcurrentModificationException rather than corrupting it.

5Bulk Methods on Map and on Synchronized Collections

Map has its own bulk methods. forEach((k, v) -> ...) passes each key and value straight to a BiConsumer, so we do not have to unpack Map.Entry objects ourselves, and replaceAll((k, v) -> newValue) updates every value in place. Map has no removeIf of its own, but its views do, and removing from a view removes from the map.

Java
Map<String, Integer> stock = new HashMap<>(Map.of("apple", 0, "pear", 4, "plum", 0));
stock.forEach((k, v) -> System.out.println(k + "=" + v)); // order not defined
stock.replaceAll((k, v) -> v + 1); // {apple=1, pear=5, plum=1}
stock.values().removeIf(v -> v == 1); // {pear=5}
stock.entrySet().removeIf(e -> e.getKey().startsWith("p")); // {}

Internal iteration also lets wrappers add behaviour around the whole loop. Collections.synchronizedList performs forEach and removeIf while holding its lock for the entire operation, so they are safe against other threads that use the same wrapper. Its iterator, and therefore the enhanced for loop, is not: each call locks separately, and the Javadoc requires us to wrap manual iteration in synchronized (list).

6Follow-up questions

Is list.forEach faster than an enhanced for loop?

For ArrayList it can be slightly faster because it skips the Iterator object and the per-element modCount check, but the difference is usually lost in the cost of the loop body, and the JIT often removes the Iterator anyway. Choose by clarity and by the control-flow needs, not by speed.

Is forEach on a stream the same as Iterable.forEach?

Not exactly. Stream.forEach on a parallel stream runs the action on several threads in no defined order, while Iterable.forEach on a List runs in list order on the calling thread. For ordered output from a parallel stream, use forEachOrdered.

Does removeIf work on every collection?

It is a default method on Collection, so every collection has it. The default version uses the iterator's remove(), so it is O(n) for linked structures and only as good as a manual loop for others; ArrayList, ArrayDeque and some others override it with faster versions. On an immutable list it throws UnsupportedOperationException if any element matches.

7Conclusion

In this answer, we saw that the enhanced for loop is external iteration, where our code controls the loop, while forEach is internal iteration, where the collection calls our lambda. Inside forEach we cannot break, update non-final locals or throw checked exceptions easily, and ArrayList.forEach checks modCount and throws ConcurrentModificationException if the list changed. removeIf beats removing in a loop on ArrayList because it marks matches and compacts in one O(n) pass instead of O(n squared) shifts. Map offers forEach, replaceAll and removeIf through its views, and synchronized wrappers run forEach and removeIf under their lock.

What to say in the interviewAbout 80 seconds aloud

Open with

The enhanced for loop is external iteration: my code pulls elements from an Iterator. forEach is internal iteration: I pass a lambda and the collection drives the loop.

Then, if they want more

That has practical consequences. Inside the lambda I can't break out early, return only acts like continue, I can't update local variables because they must be effectively final, and checked exceptions are awkward because Consumer.accept doesn't declare any, so I end up wrapping them.

So I use forEach for short side effects and a for loop when I need early exit, counters or checked exceptions.

Because the collection runs the loop, it can optimise and protect it: ArrayList.forEach loops over the array directly, notices if modCount changed and throws ConcurrentModificationException after the loop, and the synchronized wrappers run forEach and removeIf under their lock, which their iterator doesn't do. removeIf is better than removing inside a loop because on an ArrayList each single remove shifts the tail of the array, so removing many elements is O(n squared).

ArrayList.removeIf first records the matching positions in a bit set, then compacts the survivors in one pass, which is O(n), and it can't trip over its own iterator. For maps, there's forEach with a BiConsumer, replaceAll to update every value, and removeIf through entrySet, keySet or values.

About this answer

Last updated
12 November 2026
Versions it names
Java 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare Iterable.forEach with an enhanced for loop, and explain why ArrayList.removeIf...": https://scrivio-interview-library.netlify.app/java/iteration/9f6f97d697/