Forcing Java lambda expressions to capture non-final variables in Java

瘦欲@ 提交于 2020-02-22 07:55:46

问题


Is it possible to have a lambda expression capture a variable that is not effectively final?

I know that my code would work perfectly if it could capture them, currently I have to create a new variable that copies the non-final variable I want to pass into a lambda expression.

final SomeClass otherObj;

for(int i = 0; i < 10; i++) {
    int a = i;
    someObject.method(() -> otherObj.process(a, a+1))
}

I'd like to pass in 'i' instead of having to create a new temporary variable.


回答1:


You can try this with java8,

IntStream.range(0, 10).forEach(i ->{
   someObject.method(() -> otherObj.process(i, i+1))
});



回答2:


I used the java.util.concurrent.atomic package.

Here is an example:

        AtomicInteger tifCount = new AtomicInteger(0);
        try(DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("C:\\ImageStorage")) {
            ds.forEach(path -> {
                if (FileSystems.getDefault().getPathMatcher("glob:**.tif").matches(path)) {
                    tifCount.incrementAndGet();
                }
            });
        }


来源:https://stackoverflow.com/questions/31403049/forcing-java-lambda-expressions-to-capture-non-final-variables-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!