强制 Java lambda 表达式捕获 Java 中的非最终变量

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

是否可以让 lambda 表达式捕获一个实际上不是 final 的变量?

我知道如果我的代码可以捕获它们,它会完美地工作,目前我必须创建一个新变量来复制我想传递到 lambda 表达式中的非最终变量。

final SomeClass otherObj;

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

我想传入 'i' 而不是创建一个新的临时变量。

您可以尝试使用 java8、

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

我使用了 java.util.concurrent.atomic 包。

这是一个例子:

        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();
                }
            });
        }