forEach with lambda
- Java course
- Intermediate
- Lesson 103/116
- 5 min
Learn to use lambdas inside forEach.
forEach with a lambda
The forEach method runs an action for each element of a collection. Its parameter is a Consumer<T> functional interface with a single accept(T) method. With a lambda you write names.forEach(s -> System.out.println(s));.
forEach is the functional counterpart of the for-each loop. You cannot modify elements inside it; only read or produce a side effect (print, write to a file). On ordered collections it walks in insertion order.
forEach vs for-each loop
Both forms walk a collection but differ. The classic for-each: for (String s : names) { ... } — you can exit with break or continue. forEach: names.forEach(s -> ...) — no break/continue from inside the lambda.
forEach is shorter and fits functional style; but for early exit a classic for-each is preferred. For side effects (printing, summing) forEach is more concise.
Practice Sum prices with forEach
Declare List<Integer> prices = new ArrayList<>();; add 10, 20, 30. Use int[] total = {0}; to hold the sum (the lambda needs effectively final). Add each price with prices.forEach(p -> total[0] += p);. After the loop print the sum with System.out.println(total[0]);.
Starter code
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Declare List<Integer>, add 10,20,30; use a single-element array to hold the sum, sum with forEach, print
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<Integer> prices = new ArrayList<>();
prices.add(10);
prices.add(20);
prices.add(30);
int[] total = {0};
prices.forEach(p -> total[0] += p);
System.out.println(total[0]);
}
}Expected output
60
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which functional interface does forEach expect?
- Consumer Correct answer
- Comparator
- Supplier
- Runnable
Explanation: forEach expects a Consumer<T> with a single accept(T) method.
2 Match the forEach concepts
| Term | Meaning |
|---|---|
forEach(...) |
Runs an action |
Consumer<T> |
Single-arg interface |
s -> ... |
Lambda parameter |
break |
Not in forEach |
3 Complete the forEach call
names.forEach(____ -> System.out.println(s));
names.forEach(s -> System.out.println(s));
Explanation: A single-parameter lambda can be written without parentheses.