stream.foreach中的java 8局部变量 [英] java 8 local variable in stream.foreach

查看:247
本文介绍了stream.foreach中的java 8局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在lambda函数中使用局部变量,但是我得到错误:
请参阅代码中的1.和2.点。

I would like to use local variables in lambda functions but I get error: Please see the 1. and 2. points in the code.

class Foo {
    int d = 0; // 1. It compiles, but ugly, 2. doesnt compile
    public void findMax(List<List<Route>> routeLists) {
        int d = 0; // 2.Error : Local variable dd defined in an enclosing scope must be final or effectively final
        routeLists.forEach(e-> {
            e.forEach(ee -> {
                d+=ee.getDistance();    
            });

        });
        ... doing some other operation with d
    }
}

如何使用它们将它们设置为全局变量?

How can I use them whitout setting them as global variables ?

推荐答案

您不能将int用作变量,因为必须是最终的才能在流中使用。

You can't use an int as variable because it must be final to be used in a stream.

但是你可以创建一个包装int的类。

But You can create a class wrapping the int.

然后声明保持此类为最终的变量。

Then declare the variable holding this class as final.

更改内部int变量的内容。

Changing the content of the inner int variable.

public void findMax(List<List<Route>> routeLists) {
        final IntWrapper dWrapper = new IntWrapper();
        routeLists.forEach(e-> {
            e.forEach(ee -> {
                dWrapper.value += ee.getDistance();    
            });

        });

        int d = dWrapper.value;

        ... doing some other operation with d
    }

 public class IntWrapper {
    public int value;
 }

这篇关于stream.foreach中的java 8局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆