Java 收集器 groupBy 具有特定键的条件

问题描述 投票:0回答:1

我收集了一些物品:

List<PdfTitleCustomizationDto> dtoList = Arrays.asList(
            new PdfTitleCustomizationDto("Title 1", 1, "RRF", Set.of(new Role("ADMIN"))),
            new PdfTitleCustomizationDto("Title 2", 2, "Other", Set.of(new Role("USER"))),
            new PdfTitleCustomizationDto("Title 3", 3, "RRF", Set.of(new Role("ADMIN"))),
            new PdfTitleCustomizationDto("Title 4", 4, "Other", Set.of(new Role("ADMIN")))
    );

我需要按频道对其进行分组,即“RRF”或“其他”。但是,如果频道是“RRF”,我只能获得一个最小订单的标题。 所以预期的结果应该是:

{RRF=[Title 1], Other=[Title 4, Title 2]}

您有什么想法如何在一个流中做到这一点吗?

java stream collectors
1个回答
0
投票

我相信你可以使用 Collector 得到你需要的东西

看看下面的代码。

Map<String,List<PdfTitleCustomizationDto>> result = dtoList.stream()
    .collect(Collectors.groupingBy(
        PdfTitleCustomizationDto::getChannel,
        Collectors.collectingAndThen(
            Collectors.minBy(Comparator.comparingInt(PdfTitleCustomizationDto::getOrder)),
            optionalDto - > optionalDto.map(Collections::singletonList).orElse(Collections.emptyList())
        )
    ));
© www.soinside.com 2019 - 2024. All rights reserved.