I am trying to collect result of a list and organise them into a Map where the value is a Map:
private Map<Organisation, Map<LocalDate, Status>> getSummaries(final List<Status> summaries) {
return summaries
.stream()
.collect(groupingBy(Status::getOrganisation,
toMap(Status::getProcessedDate, Function.identity())));
}
I get java.lang.IllegalStateException: Duplicate key
error as getProcessedDate()
is same for different values in the list.
Is there a way I can merge multiple objects with same processeddate
into the map?
e.g say I have these objects in the the list:
Summary(ProcesseDate=2020-01-30, Organisation=ABC, status=OK, statusCount=5)
Summary(ProcesseDate=2020-01-30, Organisation=ABC, status=FAILED, statusCount=2)
Summary(ProcesseDate=2020-01-30, Organisation=APPLE, status=OK, statusCount=5)
Summary(ProcesseDate=2020-01-30, Organisation=APPLE, status=REJECTED, statusCount=5)
Values contained in the map should be:
key=ABC
value { key=2020-01-30, value= Summary(ProcesseDate=2020-01-30, Organisation=ABC, status=OK, statusCount=5), Summary(ProcesseDate=2020-01-30, Organisation=ABC, status=FAILED, statusCount=2) }
When I tried toMap(Status::getProcessedDate, Function.identity(), (v1, v2) -> v2)));
it removes one of the entries
You might just be looking for a nested grouping if you don't want to merge data and don't have unique keys:
private Map<Organisation, Map<LocalDate, List<Status>>> getSummaries(final List<Status> summaries) {
return summaries
.stream()
.collect(groupingBy(Status::getOrganisation, groupingBy(Status::getProcessedDate)));
}