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
collectingAndThenwrapper 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 useflatMapto merge them back into a single list ofItemobjects. - Getter Check: Make sure
Item::getReportDatematches your entity's actual getter method. Looking at your entity class, the field is namedreportDay—so if your getter isgetReportDay(), replace this withItem::getReportDayto 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
相关产品推荐
相关产品推荐

