问题
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