Java LinkedList forEach() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, forEach(action) calls the given Consumer once for every element of the LinkedList, from first to last. A Consumer is a small piece of code that takes one value and returns nothing, usually written as a lambda such as x -> System.out.println(x).

It does the same job as a for-each loop, in one line. It comes from the Iterable interface, so every collection has it.

An instance method of java.util.LinkedList (since Java 8): call it on a LinkedList object. Add import java.util.LinkedList; at the top of your file. It is declared by Iterable, and LinkedList implements it. forEach() was added in Java 8.

Syntax

Pass a lambda or a method reference.

Java
LinkedList<String> list = new LinkedList<>(Arrays.asList("A", "B", "C"));
list.forEach(s -> System.out.println(s));
list.forEach(System.out::println);   // same output
CallWhat it does
list.forEach(x -> ...)Runs the lambda for every element.
list.forEach(System.out::println)Prints every element on its own line.
for (E x : list) { ... }The classic loop; it also allows break and changing local variables.
list.replaceAll(op)Replaces elements instead of only visiting them.

A lambda can read local variables only if they are effectively final, which means they are never changed after being set.

Library declarations
Java
// java.util.LinkedList (default method from java.lang.Iterable)
public void forEach(Consumer<? super E> action)

Parameters

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

Return Value

Return ValueDescription
voidNothing is returned.

Compare with Similar Methods

Ways to visit every element:

MethodHow it differs
iterator()Gives you control with hasNext, next and remove.
replaceAll(op)Visits every element and stores a new value.
removeIf(filter)Visits every element and removes those that pass a test.
ArrayList.forEach()The same default method on an array-backed list.

Java Examples

Example 1 — Print a List with a Lambda and a Method Reference

Print each name in two ways, and format each line differently in a lambda.

Java
import java.util.Arrays;
import java.util.LinkedList;

public class LinkedListForEachDemo {
    public static void main(String[] args) {
        LinkedList<String> names = new LinkedList<>(Arrays.asList("Ira", "Jon", "Kai"));

        names.forEach(System.out::println);

        names.forEach(n -> System.out.println("Hello, " + n + "!"));
    }
}

How It Works

  1. A method reference. System.out::println is a short form of x -> System.out.println(x), so each name is printed on its own line.
  2. Order is kept. The elements are visited from first to last, so Ira comes first.
  3. A lambda with extra work. The second call builds a greeting from each name before printing it.
  4. The list is only read. forEach does not change the elements or the size.

Example 2 — Add Up Values Inside forEach

Total a list of numbers, using an array of one element as a changeable holder.

Java
import java.util.Arrays;
import java.util.LinkedList;

public class LinkedListForEachSum {
    public static void main(String[] args) {
        LinkedList<Integer> sales = new LinkedList<>(Arrays.asList(120, 80, 45, 200));

        int[] total = {0};
        int[] biggest = {Integer.MIN_VALUE};

        sales.forEach(s -> {
            total[0] += s;
            if (s > biggest[0]) {
                biggest[0] = s;
            }
        });

        System.out.println("total: " + total[0]);
        System.out.println("biggest: " + biggest[0]);
    }
}

How It Works

  1. A lambda cannot change an int variable. A plain int total would not compile, because lambdas only capture effectively final variables.
  2. A one-element array is the workaround. The array variable itself never changes, only the value inside it.
  3. Both results grow as the list is visited. total[0] adds each sale, and biggest[0] remembers the largest one.
  4. The answers. The sales add up to 445, and the biggest single sale is 200. A normal for-each loop would not need this trick.

Example 3 — See What forEach Does Not Allow

Pass a null action, and add an element to the list from inside the lambda.

Java
import java.util.Arrays;
import java.util.LinkedList;

public class LinkedListForEachErrors {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>(Arrays.asList("a", "b", "c"));

        try {
            list.forEach(null);
        } catch (NullPointerException e) {
            System.out.println("null action -> NullPointerException");
        }

        try {
            list.forEach(s -> list.add(s + s));
        } catch (RuntimeException e) {
            System.out.println("add inside forEach -> " + e.getClass().getSimpleName());
        }

        System.out.println("size: " + list.size());
    }
}

How It Works

  1. A null action. There is no code to run, so Java throws NullPointerException immediately.
  2. Changing the list while it is being visited. The lambda adds "aa" during the first visit.
  3. The iterator notices. When forEach asks for the next element, it detects the change and throws ConcurrentModificationException.
  4. The first change stays. One element was added before the failure, so the size is 4.

Frequently Asked Questions

It runs the given Consumer (a lambda or method reference) once for every element, from first to last.
Java 8, along with lambdas and the Consumer interface.
Use list.forEach(System.out::println), or list.forEach(x -> System.out.println(x)).
No. A lambda cannot break out of the loop. Use a normal for-each loop, or an iterator, when you need to stop early.
Lambdas can only use local variables that are effectively final. Use a field, a one-element array, or a normal loop instead.

Next: get()

Read the element at a given 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.

7 people found this page helpful