Is there a way I could simplify this and directly convert the map I got from groupingBy to a list of elements that have key and values as attributes? And not to have 2 times conversions to stream.
What I am doing here is that I fetch RiskItems and then map them to DTO, after it I need them grouped by an attribute from RiskItemDTO - the RiskDTO and then all these into a List of elements that have RiskDTO and coressponding RiskItemDTOs as elements..
riskItemRepositoryCustom.findRiskItemsByRiskTypeName(riskTypeName)
.stream()
.map(mapper::mapToDTO)
.collect(groupingBy(RiskItemDTO::getRisk))
.entrySet()
.stream()
.map( entry -> new RiskWithRiskItemsDTO(entry.getKey(),entry.getValue()))
.collect(Collectors.toList());
No, this is two separate stream operations; the result of the grouping by is the input to the second pipeline.
I know that lots of people try to make a game out of "use as few semicolons as possible", but the goal should be readability and clarity, not concision. In general, I think it is better to be honest about what is going on, and write it as two separate stream operations:
Map<RiskItemDTO, List<RiskItem> itemsByRisk = repo.findRiskItemsByRiskTypeName(riskTypeName)
.stream()
.map(mapper::mapToDTO)
.collect(groupingBy(RiskItemDTO::getRisk));
List<RiskWithRiskItemsDTO> list = itemsByRisk.entrySet().stream()
.map( entry -> new RiskWithRiskItemsDTO(entry.getKey(),entry.getValue()))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With