java 从 lambda 表达式引用的局部变量必须是最终的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40493738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:16:28  来源:igfitidea点击:

Local variables referenced from a lambda expression must be final

java

提问by axiorema

I′m trying to create a getValue()function from a pojo that use summatory of details class values in this sense:

我正在尝试getValue()从 pojo创建一个函数,在这个意义上使用细节类值的汇总:

@Transient
public BigDecimal getValue() {
   BigDecimal sum = new BigDecimal(0);

   details.stream().forEach((detail) -> {
      sum = sum.add(detail.getValue());
   });

   return sum;
}

but I don't know why this the line sum = sum.add(detail.getValue());provoke this error:

但我不知道为什么这条线sum = sum.add(detail.getValue());会引发此错误:

local variables referenced from a lambda expression must be final or effectively final

从 lambda 表达式引用的局部变量必须是最终的或有效的最终变量

Can you say me what's I'am doing wrong. Thanks.

你能告诉我我做错了什么吗?谢谢。

回答by Louis Wasserman

You cannotmodify variables from inside a lambda. That's just not a thing you're allowed to do.

不能从 lambda 内部修改变量。这不是你被允许做的事情。

What you cando here is write this method as

可以在这里做的是把这个方法写成

return details.stream()
    .map(Detail::getValue)
    .reduce(BigDecimal.ZERO, BigDecimal::add);

回答by axiorema

Ok, just do not use the lambda expression in the foreach loop

好的,只是不要在 foreach 循环中使用 lambda 表达式

@Transient
public BigDecimal getValue() {
   BigDecimal sum = new BigDecimal(0);

   for (Detail detail : details) {
      sum = sum.add(detail.getValue());
   }

   return sum;
}

回答by Rocky

this is my way to avoid final p in the loop and it worked.

这是我在循环中避免最终 p 的方法并且它起作用了。

public void getSolutionInfo(){      
ArrayList<Node> graph = Main.graph; 

    for(int p=1;p<=Pmax;p++) {          
        final int p2=p;
        System.out.printf("number of node with priority p = %d is %d ",p, graph.stream().filter(node->node.getPriority()==p2).count()); 
    }