简体   繁体   中英

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());

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM