Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groupingBy & Java 8 - after groupingBy convert map to a list of objects

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());
like image 820
mladibejn Avatar asked Feb 07 '23 23:02

mladibejn


1 Answers

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());
like image 72
Brian Goetz Avatar answered Feb 12 '23 09:02

Brian Goetz