本文介绍了如何在Java 8 Lambdas中使用非最终变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Java 8 lambda中使用非最终变量.它会引发编译错误,提示封闭范围中定义的局部变量日期必须是最终的或实际上是最终的"
How can I use non-final variable in Java 8 lambda. It throws compilation error saying 'Local variable date defined in an enclosing scope must be final or effectively final'
我实际上想实现以下目标
I actually want to achieve the following
public Integer getTotal(Date date1, Date date2) {
if(date2 == null || a few more conditions) {
date2 = someOtherDate;
}
return someList.stream().filter(filter based on date1 and date2).map(Mapping Function).reduce(Addition);
}
我该如何实现?它引发date2的编译错误.谢谢,
How do I achieve this? It throws comilation error for date2.Thanks,
推荐答案
使用另一个可以一次启动的变量.
Use another variable that you can initiate once.
final Date tmpDate;
if(date2 == null || a few more conditions) {
tmpDate = someOtherDate;
} else {
tmpDate = date2;
}
这篇关于如何在Java 8 Lambdas中使用非最终变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!