In Java 8 and later, forEach(action) runs action once for every element of an ArrayList, from index 0 to the end. The action is a Consumer<E>: it takes an element and returns nothing.
It is a compact alternative to the enhanced for loop. The lambda cannot use break or continue, and local variables it uses must be effectively final, so a plain loop is often easier when you need a counter or an early exit.
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe. forEach has been available since Java 8 as a default method of Iterable; ArrayList overrides it with the same behavior.
Syntax
Pass a lambda or a method reference.
Java
List<String> list = new ArrayList<>(Arrays.asList("a", "b"));
list.forEach(s -> System.out.println(s)); // lambda
list.forEach(System.out::println); // method reference
Call
What it does
list.forEach(x -> ...)
Runs the lambda for each element.
list.forEach(System.out::println)
Prints every element on its own line.
for (E x : list) { ... }
Enhanced for loop; allows break and continue.
list.stream().forEach(...)
Stream version; for a simple loop, list.forEach is enough.
Inside the lambda, return acts like continue: it ends the action for the current element and the loop moves on to the next one.
Library declarations
Java
// java.util.ArrayList<E>
public void forEach(Consumer<? super E> action)
// Declared in Iterable<T> (default method since Java 8)
// java.util.function.Consumer<T>
void accept(T t)
Parameters
Parameter
Description
action (Consumer<? super E>)
The code to run for each element. Must not be null.
Return Value
Return Value
Description
void
Nothing is returned; all effects come from the action.
visit a
stopped: ConcurrentModificationException
list now: [a, b, c, d]
How It Works
Visit a. The action prints "visit a" and then adds "d" to the very list being walked.
Change detected.ArrayList's forEach checks its modification count before moving to each next element, sees the add, and stops without visiting b.
Exception after the loop. It then throws ConcurrentModificationException, which the catch block reports.
Change kept. The add itself succeeded, so the list now ends with d. Collect new elements in a separate list and add them after the loop instead.
Frequently Asked Questions
Java 8, as a default method of the Iterable interface, together with lambda expressions.
forEach takes a lambda and is shorter. A for loop can use break, continue, and ordinary local variables, and can return from the enclosing method.
No. return inside the lambda only skips to the next element. Use a regular for loop when you need to stop early.
No. Changing the same list from the action causes ConcurrentModificationException. Use removeIf, replaceAll, or a separate list.
Lambdas capture the value of local variables, so Java does not allow those variables to be reassigned. Use a field, an array element, or an object to accumulate results.