CKTIS / Java
Iterable.forEach: an action for each element
Call `forEach` on an `Iterable` to run an action for each element. If the object specifies an iteration order, the method follows it unless the implementing class specifies otherwise.
Version: Java SE 21
Syntax
default void forEach(Consumer<? super T> action)
iterable.forEach(action);Iterable.forEach(Consumer) is a default method of java.lang.Iterable<T>, available since Java 8. You call it on an object you can iterate over, such as a list. Its return type is void: it does not return a new collection.
The argument type is java.util.function.Consumer<? super T>. This lets you pass an action that accepts an element as T or as a supertype of T. Its accept method takes one argument and returns no result. You can supply the action as a lambda, name -> System.out.println(name), or as a method reference, System.out::println.
The default implementation works like an enhanced for loop that calls action.accept(element) for each element. If the iteration order is specified, forEach follows it unless the implementing class specifies otherwise. The iteration order of a List is from the first element to the last. Do not assume a particular order if the object does not guarantee one.
If the action throws an exception, processing stops and the exception propagates to the caller. Passing null as the action causes a NullPointerException. Do not modify the element source inside the action: the method's behavior is then unspecified unless an overriding class documents a concurrent modification policy.
Examples
import java.util.List;
public class Main {
public static void main(String[] args) {
Iterable<String> names = List.of("Ada", "Linus", "Grace");
names.forEach(System.out::println);
}
}Result
Ada Linus Grace
The method reference `System.out::println` prints each name on its own line. The expected order is `Ada`, `Linus`, `Grace`, matching the list order.
Related lessons
- Java · Lesson 64 · Basic · Version: 2