public Double getUnitsBefore(Date recordDate) {
double eligibleUnits = 0;
ageBucket.forEach((dateStr, units) -> {
try {
Date date = DFT.parse(dateStr);
if (date.before(recordDate)) {
//TODO These are eligible units for dividend.
eligibleUnits = eligibleUnits + units.doubleValue(); //TODO
}
} catch(ParseException e) {
e.printStackTrace();
}
});
return eligibleUnits;
}
eligibleUnits = eligibleUnits + units.doubleValue();
无法在Java 8中编译。我如何实现这一目标?我需要在日期早于记录日期之前加总。答案 0 :(得分:4)
改为使用流:
return ageBucket.entrySet()
.stream()
.filter(e -> DFT.parse(e.getKey()).before(recordDate))
.mapToDouble(Map.Entry::getValue)
.sum();
答案 1 :(得分:1)
它不会编译,因为变量eligibleUtins
不是effectively final。如果你想使用lambdas,那么将代码重组为数据流(如@shmosel answer中),不会改变变量
否则,如果你想改变变量,那么使用for循环重写
double eligibleUnits = 0;
for(Entry entry : ageBucket.entrySet(){
String dateStr = entry.getKey();
units = entry.getValue();
// the rest of your code
}
return eligibleUnits;