Home Java ArrayDeque Methods forEach() Java ArrayDeque forEach() Method Definition In Java, forEach(action) runs the given Consumer once for every element of an ArrayDeque, in head-to-tail order. The action is usually a lambda like s -> System.out.println(s) or a method reference like System.out::println.
It returns nothing and does not change the deque by itself. It is a compact alternative to the enhanced for loop or an explicit iterator() .
An instance method of java.util.ArrayDeque (Java 1.6+): a resizable-array deque with no capacity limit, no null elements, and no thread safety . forEach has been available since Java 8 (as a default method of Iterable); newer JDKs override it in ArrayDeque with the same result.
Syntax Pass a lambda or method reference that accepts one element.
deque.forEach(s -> System.out.println("item: " + s));
deque.forEach(System.out::println); Call What it does deque.forEach(x -> ...)Runs the lambda for each element, head to tail. deque.forEach(System.out::println)Prints each element on its own line. for (E x : deque) { ... }Classic loop with the same order. deque.forEach(null)Throws NullPointerException.
A lambda can only use local variables that are effectively final, so you cannot write sum += x with a plain int sum. Use a one-element array, an AtomicInteger, or a stream such as deque.stream().mapToInt(...).sum().
Library declarations // java.util.ArrayDeque<E>
public void forEach(Consumer<? super E> action)
// Declared in Iterable<T> (default method since Java 8) Parameters Parameter Description actionRequired. A Consumer that is called with each element. Must not be null.
Return Value Return Value Description voidNothing is returned.
Compare with Similar Methods forEach and its alternatives:
Method How it differs Enhanced for loop Same order; allows break, continue, and changing local variables. iterator()Lets you remove elements safely with it.remove(). removeIf(filter)A lambda that decides which elements to delete. spliterator() / stream()For filtering, mapping, and summing with streams.
Java Examples 1. Lambda 2. Method reference 3. Build a path Example 1 — Greet Everyone with a Lambda Run one lambda for each name in the deque.
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class ArrayDequeForEachDemo {
public static void main(String[] args) {
Deque<String> names = new ArrayDeque<>(Arrays.asList("Ann", "Bob", "Cy"));
names.forEach(n -> System.out.println("Hello, " + n));
}
} Hello, Ann
Hello, Bob
Hello, Cy How It Works The lambda. n -> System.out.println("Hello, " + n) takes one name and prints a greeting.Called once per element. forEach passes Ann, then Bob, then Cy to it.Head-to-tail order. The names come out in the same order as in the list used to build the deque.No index needed. Unlike a counting loop, you never deal with positions; an ArrayDeque has no index access anyway.Example 2 — Method Reference and a Running Total Print a pushed stack with System.out::println, then add up the values with a one-element array.
import java.util.ArrayDeque;
import java.util.Deque;
public class ArrayDequeForEachTotal {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.forEach(System.out::println);
int[] total = {0};
stack.forEach(n -> total[0] += n);
System.out.println("total = " + total[0]);
}
} How It Works Top first. The values were pushed, so the head is 3 and forEach prints 3, 2, 1.Method reference. System.out::println is shorthand for n -> System.out.println(n).Effectively final workaround. The array variable total never changes; only its single slot does, so the lambda may update total[0].The sum. 3 + 2 + 1 gives total = 6.Example 3 — Build a Path String Join path parts with a StringBuilder inside forEach, then compare with a classic loop.
import java.util.ArrayDeque;
import java.util.Deque;
public class ArrayDequeForEachPath {
public static void main(String[] args) {
Deque<String> path = new ArrayDeque<>();
path.addLast("usr");
path.addLast("local");
path.addLast("bin");
StringBuilder sb = new StringBuilder();
path.forEach(part -> sb.append('/').append(part));
System.out.println(sb);
for (String part : path) {
System.out.println(part + " has " + part.length() + " letters");
}
}
} /usr/local/bin
usr has 3 letters
local has 5 letters
bin has 3 letters How It Works A mutable helper. sb is a StringBuilder. The variable itself is effectively final, but the object it points to can change.Append each part. For every element the lambda adds a slash and the part, building /usr/local/bin.Same order in a for loop. The enhanced for loop visits the same three parts in the same order.Pick by need. forEach is concise for one action; the classic loop is handier for several statements or break.Frequently Asked Questions What does ArrayDeque forEach() do? It runs the given action once for each element, from head to tail.
Which Java version added forEach()? Java 8, as a default method of the Iterable interface.
Can I modify a local variable inside forEach()? Not directly. Local variables used in a lambda must be effectively final. Use a one-element array, an AtomicInteger, or a stream instead.
Can I remove elements inside forEach()? No. Changing the deque during forEach can throw ConcurrentModificationException. Use removeIf() or an iterator.
In what order does forEach() visit a stack? Head to tail, which is top to bottom for a stack built with push().
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