Home Java LinkedList Methods forEach() Java LinkedList forEach() Method 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.
LinkedList<String> list = new LinkedList<>(Arrays.asList("A", "B", "C"));
list.forEach(s -> System.out.println(s));
list.forEach(System.out::println); // same output Call What 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.util.LinkedList (default method from java.lang.Iterable)
public void forEach(Consumer<? super E> action) Parameters Parameter Description action (Consumer<? super E>)The code to run for each element. It must not be null.
Return Value Return Value Description voidNothing is returned.
Important
This method needs Java 8 or later. A null action throws NullPointerException. You cannot use break or return to stop the loop early, and a lambda cannot change a normal local variable such as int total. If the lambda adds or removes elements of the same list, you get a ConcurrentModificationException.
Compare with Similar Methods Ways to visit every element:
Java Examples 1. Print every element 2. Accumulate a result 3. Null and changes 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.
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 + "!"));
}
} Ira
Jon
Kai
Hello, Ira!
Hello, Jon!
Hello, Kai! How It Works 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.Order is kept. The elements are visited from first to last, so Ira comes first.A lambda with extra work. The second call builds a greeting from each name before printing it.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.
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 A lambda cannot change an int variable. A plain int total would not compile, because lambdas only capture effectively final variables.A one-element array is the workaround. The array variable itself never changes, only the value inside it.Both results grow as the list is visited. total[0] adds each sale, and biggest[0] remembers the largest one.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.
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());
}
} null action -> NullPointerException
add inside forEach -> ConcurrentModificationException
size: 4 How It Works A null action. There is no code to run, so Java throws NullPointerException immediately.Changing the list while it is being visited. The lambda adds "aa" during the first visit.The iterator notices. When forEach asks for the next element, it detects the change and throws ConcurrentModificationException.The first change stays. One element was added before the failure, so the size is 4.Frequently Asked Questions What does LinkedList forEach() do? It runs the given Consumer (a lambda or method reference) once for every element, from first to last.
Which Java version added forEach()? Java 8, along with lambdas and the Consumer interface.
How do I print every element of a LinkedList with forEach? Use list.forEach(System.out::println), or list.forEach(x -> System.out.println(x)).
Can I use break inside forEach()? No. A lambda cannot break out of the loop. Use a normal for-each loop, or an iterator, when you need to stop early.
Why can I not change a local variable inside forEach()? Lambdas can only use local variables that are effectively final. Use a field, a one-element array, or a normal loop instead.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion