Basic forEach Syntax with Lambda Expressions
You'll learn how to use forEach with lambda expressions to perform actions on each element in a stream.
What is forEach?
You already know that forEach is a terminal operation—it consumes the stream and triggers the pipeline. Now let's see how to actually use it with lambda expressions to do something with each element.
The forEach method takes a Consumer<T> as its parameter. In plain English: it accepts a function that takes one argument (the stream element) and returns nothing. This makes it perfect for side effects like printing, logging, or updating external state.
Basic Syntax
The general pattern looks like this:
stream.forEach(element -> /* do something with element */);
Simple Examples
Printing each element:
Stream.of("apple", "banana", "cherry")
.forEach(fruit -> System.out.println(fruit));
Logging with more context:
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
numbers.stream()
.forEach(n -> System.out.println("Processing: " + n));
Performing calculations (though results aren't returned):
Stream.of(10, 20, 30)
.forEach(value -> {
int doubled = value * 2;
System.out.println("Doubled: " + doubled);
});
The Lambda Structure
The lambda element -> action is shorthand for "take this element and do this action." The element parameter name is your choice—use descriptive names like fruit, n, or value for clarity.
Key Takeaway: forEach with lambda expressions lets you execute an action on every stream element using the concise syntax element -> action, making it ideal for operations like printing or logging where you don't need to return a result.