here my current code to perform a cumulative sum over a hash table Map< String,Double>
START.forEach((k,v)->{
sum += v;
END.put(k, sum);
});
or, alternately,
END= START.entrySet()
.stream()
.collect(
Collectors.toMap(entry -> entry.getKey(),
entry -> {
sum += entry.getValue();
return sum;
}));
But I have the following error:
Local variable sum defined in an enclosing scope must be final or effectively final
How could I fix it?
I wouldn't want to use the standard for loop like that:
Iterator it = START.entrySet().iterator();
double sum = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String key = (String) pair.getKey();
Double value = (Double) pair.getValue();
sum+=value;
END.put(date, sum);
}
START
------------
|first | 1 |
|second| 5 |
|third | 4 |
END
|first | 1 |
|second| 6 |
|third | 10 |