Skip to content
CodeKruPro

Changing a local variable inside a lambda

QuizEasy-MediumJava only

A local variable is one declared inside a method. Why does this not compile, and what is a good fix?

int count = 0;
List.of(1, 2).forEach(i -> count++);
  • Local variables used in a lambda must be final or effectively final; use long count = list.stream().count() or a stream that computes the result
  • forEach cannot take a lambda
  • count must be declared as static inside the method
  • The lambda needs braces around count++

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in