You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data JPA查询结果超20条时按日分组并限制每日10条

Solution for Grouping with Per-Day Limit

Got it, let's fix that grouping logic you're stuck on! The key is to use a downstream collector in groupingBy to limit each date group to 10 items, then flatten those groups back into a single list. Here's the complete implementation with explanations:

public List<Item> getItemsForRequiredDays(int days) {
    LocalDate daysAgoDate = LocalDate.now().minusDays(days);
    List<Item> items = itemRepository.findAllWithDateAfter(daysAgoDate);
    int size = items.size();
    
    if (size > 20) {
        return items.stream()
                .limit(20) // First take the top 20 items (already sorted by reportDate desc from your repo query)
                .collect(Collectors.groupingBy(
                        Item::getReportDate, // Group by the report date (double-check your getter matches the entity field!)
                        // For each group, collect to list then keep only first 10 items
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                groupList -> groupList.stream().limit(10).collect(Collectors.toList())
                        )
                ))
                // Flatten all grouped lists into one single List<Item>
                .values()
                .stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
    } else {
        return items;
    }
}

Key Details:

  • Grouping with Limit: The collectingAndThen wrapper lets us first collect all items in a date group into a list, then immediately truncate it to the first 10 entries.
  • Flattening Groups: After grouping, we extract all the grouped lists with .values(), then use flatMap to merge them back into a single list of Item objects.
  • Getter Check: Make sure Item::getReportDate matches your entity's actual getter method. Looking at your entity class, the field is named reportDay—so if your getter is getReportDay(), replace this with Item::getReportDay to avoid runtime errors!

This implementation follows your requirements exactly: cap the initial result at 20 items, then ensure no more than 10 items are kept per report date.

内容的提问来源于stack exchange,提问作者miroha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:33:12