Question
How can I modify a local variable when using a lambda expression in Java?
int ordinal = 0;
list.forEach(s -> {
s.setOrdinal(ordinal);
ordinal++;
});
Answer
In Java, local variables referenced from a lambda expression must be effectively final. This means that you cannot modify local variables like 'ordinal' after it's been established. To work around this limitation, you can use an array or a mutable wrapper class.
AtomicInteger ordinal = new AtomicInteger(0);
list.forEach(s -> {
s.setOrdinal(ordinal.getAndIncrement());
});
Causes
- Java's lambda expressions can only access final or effectively final local variables.
- If a variable is modified within the lambda, it violates this finality rule, leading to a compile error.
Solutions
- Use an array to hold the variable and modify the array element instead.
- Utilize a mutable object, like an instance of AtomicInteger, to allow modification.
Common Mistakes
Mistake: Trying to modify a primitive variable inside a lambda.
Solution: Use a mutable data structure like AtomicInteger or an array.
Mistake: Assuming lambda expressions can access non-final variables freely.
Solution: Ensure that any variable accessed is either declared final or effectively final.
Helpers
- Java lambda variables
- modify local variable lambda Java
- Java lambda expression compile error
- effective final variable lambda