3
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;
}
  • As you know line eligibleUnits = eligibleUnits + units.doubleValue(); does not compile in Java 8. How do i achieve this? I need to sum only when date is before record date.
shmosel
  • 49,289
  • 6
  • 73
  • 138
Jigar Naik
  • 1,946
  • 5
  • 29
  • 60

2 Answers2

5

Use a stream instead:

return ageBucket.entrySet()
        .stream()
        .filter(e -> DFT.parse(e.getKey()).before(recordDate))
        .mapToDouble(Map.Entry::getValue)
        .sum();
shmosel
  • 49,289
  • 6
  • 73
  • 138
1

It does not compile because variable eligibleUtins is not effectively final. If you want to use lambdas then restructure you code as flow of data (as in @shmosel answer) that does not change variables

Otherwise if you want to mutate variable then rewrite using a for loop

double eligibleUnits = 0;
for(Entry entry : ageBucket.entrySet(){
    String dateStr = entry.getKey();
    units = entry.getValue();
    // the rest of your code
}
return eligibleUnits;
Nazarii Bardiuk
  • 4,272
  • 1
  • 19
  • 22