CKTIS / Java
Stream.forEach: practical reference
Stream.forEach: practical reference: forEach is a terminal operation that invokes a Consumer for every element but explicitly does not guarantee encounter order in a parallel pipeline.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Stream.forEach(...)forEach is a terminal operation that invokes a Consumer for every element but explicitly does not guarantee encounter order in a parallel pipeline.
Use it for independent per-element effects when order is irrelevant; choose forEachOrdered when the effects must follow encounter order.
Actions may run in different threads and at different times, so shared-state mutation needs synchronization and often defeats parallelism.
A null Consumer causes NullPointerException; an action exception terminates processing, and the stream cannot be reused after the call.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
java.util.stream.Stream.of("a", "b").forEach(System.out::println);
}
}
Result
a b
The example exercises the documented element in a small deterministic program and compares exact standard output.