Java8 Effectively Final compile time error on non final variable

后端 未结 1 1202
盖世英雄少女心
盖世英雄少女心 2020-12-16 23:34

I\'m trying to change the boolean variable inside java8 forEach loop to true which is non final. But I\'m getting following error : Local variable required defined in an enc

相关标签:
1条回答
  • 2020-12-17 00:36

    You cannot change the local variable from the body of lambda expression. There are several ways to overcome this:

    • In this particular case you can just set boolean required = !map.isEmpty(); without any lambda expression. If you want to set it based on some condition, you can use the Stream API:

      boolean required = map.entrySet().stream().anyMatch(entry -> ...);
      

      This solution is the most preferred.

    • Convert the required variable to the field of the enclosing class.

    • The most dirty way: declare a one-element array: boolean[] required = {false}; and set this element instead: required[0] = true;
    0 讨论(0)
提交回复
热议问题