I am provided with a List<Result>
The Result class has a number of fields of which five are of interest
class Result {
public enum SESSION_TYPE {
NIGHT,
DAY
}
private SESSION_TYPE sessionType;
private String sessionDateTime;
private String sessionDate;
private Double consumed;
private Double cost;
...
getters and setters
}
I have created a map as follows
Map<String,List<Result>> dailyResults = results.stream().collect(Collectors.groupingBy(Result::getSessionDate));
I would now like to create a new map keyed on the same sessionDate which contains the summed consumed and cost fields grouped by the SESSION_TYPE, thus
Map<String, Map<String,SessionDetail>> sessionResults
i.e., Map<SessionDate, Map<SessionType,SessionDeatail>>
where the SessionDetail is a record as follows -
record SessionDetail(Result.SESSION_TYPE sessionType, Double consumedTotal, Double costTotal) {};
I've spent some time on this without achieving the desired result. Any help would be much appreciated.
You can do as follows:
Here is some data.
The original results can be first categorized by the
Date
. Then usingtoMap
, take thesession type
as the key and then create a new instance, summing the values in the previous instance to the one just encountered.Print the results as follows:
prints
The above works without making any changes to your classes. Since record values are final a new record much be created to replace the previous one using the accumulated sums.