Java ArrayDeque forEach() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
ArrayDeque

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.

Java
deque.forEach(s -> System.out.println("item: " + s));
deque.forEach(System.out::println);
CallWhat 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
// java.util.ArrayDeque<E>
public void forEach(Consumer<? super E> action)

// Declared in Iterable<T> (default method since Java 8)

Parameters

ParameterDescription
actionRequired. A Consumer that is called with each element. Must not be null.

Return Value

Return ValueDescription
voidNothing is returned.

Compare with Similar Methods

forEach and its alternatives:

MethodHow it differs
Enhanced for loopSame 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

Example 1 — Greet Everyone with a Lambda

Run one lambda for each name in the deque.

Java
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));
    }
}

How It Works

  1. The lambda. n -> System.out.println("Hello, " + n) takes one name and prints a greeting.
  2. Called once per element. forEach passes Ann, then Bob, then Cy to it.
  3. Head-to-tail order. The names come out in the same order as in the list used to build the deque.
  4. 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.

Java
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

  1. Top first. The values were pushed, so the head is 3 and forEach prints 3, 2, 1.
  2. Method reference. System.out::println is shorthand for n -> System.out.println(n).
  3. Effectively final workaround. The array variable total never changes; only its single slot does, so the lambda may update total[0].
  4. 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.

Java
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");
        }
    }
}

How It Works

  1. A mutable helper. sb is a StringBuilder. The variable itself is effectively final, but the object it points to can change.
  2. Append each part. For every element the lambda adds a slash and the part, building /usr/local/bin.
  3. Same order in a for loop. The enhanced for loop visits the same three parts in the same order.
  4. Pick by need. forEach is concise for one action; the classic loop is handier for several statements or break.

Frequently Asked Questions

It runs the given action once for each element, from head to tail.
Java 8, as a default method of the Iterable interface.
Not directly. Local variables used in a lambda must be effectively final. Use a one-element array, an AtomicInteger, or a stream instead.
No. Changing the deque during forEach can throw ConcurrentModificationException. Use removeIf() or an iterator.
Head to tail, which is top to bottom for a stack built with push().

Next: getFirst()

Read the first element; throws if empty.

getFirst() 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