Quick revision
The short answer
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).
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
| Need | Enhanced for | forEach(lambda) |
|---|---|---|
| Stop early | break | Not possible; use a stream's takeWhile or anyMatch |
| Update a local variable | Yes | Only effectively final locals can be read |
| Checked exceptions | Propagate normally | Must be caught inside the lambda |
| Collection controls traversal | No | Yes: 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.
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).
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.
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.
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.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
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/