Issue
I have a java object like this Map<Integer, Long> monthCaseCountMap
This object contains data in the format like below :
202103, 2
202104, 4
202105, 0
202106, 9
.
.
.
.
202202, 10
First value is a month key, second value is case count.
I need to create a monthly rollover data or accumulation of case count month by month.
The result should look like -
202103, 2
202104, 6
202105, 6
202106, 15
.
.
.
.
202202, 98
How can we do this in using Java streams or using any other method.
Thank you @eritren for providing the correct solution.
Solution
Another option could be to use AtomicLong to store the sum and collect the accumulated values in to a new map:
Map<Integer, Long> monthCaseCountMap = Map.of( 202103, 2L,
202104, 4L,
202105, 0L,
202106, 9L);
AtomicLong sum = new AtomicLong(0L);
Map<Integer, Long> accumulated =
monthCaseCountMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, e -> sum.addAndGet(e.getValue())));
Answered By - Eritrean
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.