Java ArrayList forEach() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
ArrayList

Definition

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
CallWhat 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

ParameterDescription
action (Consumer<? super E>)The code to run for each element. Must not be null.

Return Value

Return ValueDescription
voidNothing is returned; all effects come from the action.

Compare with Similar Methods

Other ways to process every element:

MethodHow it differs
iterator()An explicit loop that can also remove elements.
replaceAll(op)Replaces each element with a new value.
removeIf(filter)Removes elements that match a condition.
spliterator()Has forEachRemaining, used by streams.

Java Examples

Example 1 — Print Every Element Two Ways

Print each language with a method reference, then with a lambda that adds its length.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListForEachDemo {
    public static void main(String[] args) {
        List<String> langs = new ArrayList<>(Arrays.asList("Java", "Kotlin", "Scala"));

        langs.forEach(System.out::println);
        langs.forEach(l -> System.out.println(l + " has " + l.length() + " letters"));
    }
}

How It Works

  1. Method reference. System.out::println is passed as the action, so each element is printed unchanged.
  2. In order. forEach visits index 0, 1, and 2, so the languages appear in list order.
  3. Lambda. The second action builds a sentence from each element and its length().
  4. Nothing returned. forEach itself returns void; everything you see comes from what the action does.

Example 2 — Total Up Values with forEach

Add up step counts and record a goal check for each day.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListForEachSum {
    public static void main(String[] args) {
        List<Integer> steps = new ArrayList<>(Arrays.asList(3200, 4800, 2500));
        int[] total = {0};
        List<String> report = new ArrayList<>();

        steps.forEach(s -> {
            total[0] += s;
            report.add(s >= 3000 ? "goal" : "short");
        });

        System.out.println("total steps: " + total[0]);
        System.out.println("days: " + report);
    }
}

How It Works

  1. No plain int counter. A lambda cannot reassign a local variable, so the running total lives in a one-element array, total[0].
  2. Block lambda. The braces let the action run two statements for each element.
  3. A different list. Adding to report is fine, because report is not the list being looped over.
  4. Result. 3200 + 4800 + 2500 is 10500, and only 2500 is below the 3000-step goal.

Example 3 — Do Not Change the List Inside forEach

Adding to the same list from inside the action stops the loop with an exception.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.List;

public class ArrayListForEachModify {
    public static void main(String[] args) {
        List<String> queue = new ArrayList<>(Arrays.asList("a", "b", "c"));

        try {
            queue.forEach(s -> {
                System.out.println("visit " + s);
                if (s.equals("a")) {
                    queue.add("d");
                }
            });
        } catch (ConcurrentModificationException e) {
            System.out.println("stopped: " + e.getClass().getSimpleName());
        }
        System.out.println("list now: " + queue);
    }
}

How It Works

  1. Visit a. The action prints "visit a" and then adds "d" to the very list being walked.
  2. Change detected. ArrayList's forEach checks its modification count before moving to each next element, sees the add, and stops without visiting b.
  3. Exception after the loop. It then throws ConcurrentModificationException, which the catch block reports.
  4. 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.

Next: get()

Read the element at an index.

get() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful