Video in progress
Between stream().forEach() and a plain for-each loop, which do you pick and when?
For a simple iteration that returns no result, a for-each loop is often simpler: break, return and checked exceptions work. forEach is convenient for a side effect at the end of a filter/map chain.
📖 Answer
The two variants look the same:
for (Order o : orders) {
send(o);
}
orders.forEach(this::send);
But the loop is more convenient in several ways:
- if you need
breakorcontinue: they don't exist inside a lambda; - changing an outer variable (a counter, a sum): inside a lambda there is the effectively final restriction;
- if you call a method that throws a checked exception like
IOException: in a lambda you have to wrap it in try/catch; - debugging and reading the stack trace are easier.
As for stream().forEach, use it only at the end of a chain, and if you need a result, use collect/toList. The following is a widespread anti-pattern:
List<String> result = new ArrayList<>();
users.stream().filter(User::active).forEach(u -> result.add(u.email()));
// the right way: users.stream().filter(User::active).map(User::email).toList();
One more subtle difference: in a parallel stream forEach doesn't preserve order; if you need it, use forEachOrdered.
Sign up to mark studied questions and save your progress.