我想总结一个整数列表.它的工作原理如下,但语法感觉不对.代码可以优化吗?
Map<String, Integer> integers;
integers.values().stream().mapToInt(i -> i).sum();
Run Code Online (Sandbox Code Playgroud) lambda表达式中使用的变量应该是final或者有效的final
当我尝试使用calTz它时显示此错误.
private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) {
try {
cal.getComponents().getComponents("VTIMEZONE").forEach(component -> {
VTimeZone v = (VTimeZone) component;
v.getTimeZoneId();
if (calTz == null) {
calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
}
});
} catch (Exception e) {
log.warn("Unable to determine ical timezone", e);
}
return null;
}
Run Code Online (Sandbox Code Playgroud) 当我编写这段代码时,我得到一个编译时错误,上面写着: 'lambdas中的变量必须是最终的或有效的最终'.
现在,我得到这个从行中删除i:
futureLists.add(executorService.submit(() - >"Hello world"+ i));
解决了这个问题.
但我想知道为什么存在这样的要求?
根据JLS,它说的是:
使用但未在lambda表达式中声明的任何局部变量,形式参数或异常参数必须声明为final或有效final,否则在尝试使用时会发生编译时错误.
但它没有说明,为什么存在这样的要求.但是为什么Java工程师对lambdas强制执行这样的要求呢?
public class test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Future<String>> futureLists = new ArrayList<>();
for (int i = 0; i < 20; i++) {
futureLists.add(executorService.submit( () -> "Hello world" + i));
}
for (Future<String> itr:futureLists) {
System.out.println(itr.get());
}
}
}
Run Code Online (Sandbox Code Playgroud)