Video in progress

Why can't you modify an outer local variable inside a lambda?

A lambda can only read an outer local variable, and it must be final or "effectively final". The reason: the lambda takes a copy of the variable, and it may run on another thread or later.

📖 Answer

int count = 0;
orders.forEach(o -> count++);   // compile error

The error message: "Variable used in lambda expression should be final or effectively final". Effectively final means a variable that isn't declared final but hasn't changed after it was assigned once.

Why? A local variable lives on the stack and disappears when the method ends. A lambda can outlive it (for example, if it is handed to another thread). So Java copies the value into the lambda. If the original variable changed, it would diverge from the copy, and to prevent that, modification is forbidden.

The right solution is to hand the computation to the stream itself:

long count = orders.stream().filter(Order::paid).count();
int total = orders.stream().mapToInt(Order::amount).sum();

Working around it with int[] counter = {0} or an AtomicInteger technically works, but it's usually a sign you wrote the code the wrong way.

This restriction doesn't apply to class fields and this: a lambda can modify them.