问题描述
我正在尝试将java8 forEach循环中的布尔变量更改为true,这是非final。但是我得到了以下错误:在封闭范围内定义的本地变量必须是最终的或有效的最终。
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 enclosing scope must be final or effectively final.
如何解决此错误?
代码:
boolean required = false;
这是我在函数中创建的变量。
This is the variable I have created in the function.
现在我正在尝试更改它:
Now when I'm trying to change it :
map.forEach((key, value) -> {
System.out.println("Key : " + key + " Value : " + value);
required = true;
});
我收到错误:在封闭范围内定义的本地变量必须是最终的或有效的最终。
I'm getting the error : Local variable required defined in an enclosing scope must be final or effectively final.
为什么会出现此错误以及如何解决?
Why this error is arising and how to resolve it?
推荐答案
您无法从lambda表达式的主体更改局部变量。有几种方法可以解决这个问题:
You cannot change the local variable from the body of lambda expression. There are several ways to overcome this:
-
在这种特殊情况下你可以设置
boolean required = !map.isEmpty();
没有任何lambda表达式。如果你想根据某些条件设置它,你可以使用Stream API:
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 -> ...);
此解决方案是首选。
将必需的
变量转换为封闭类的字段。
Convert the required
variable to the field of the enclosing class.
这篇关于Java8有效地对非最终变量进行最终编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!