Spring Boot 构建API响应时动态补全DB缺失的近12个月参与统计数据
解决方案
你原有逻辑的问题在于生成List<Participant>时仍然只遍历了仅包含有数据月份的participantAggResults,直接改用已经补全了12个月数据的monthParticipantMap构造结果列表即可,同时调整不合理的空返回逻辑,修改后代码如下:
public ParticipantReportDto getParticipantsReport( List<ParticipantAggResult> participantAggResults, ReportTrendType trendType) { // 移除原有的空集合直接返回逻辑,无数据时也要生成12个月份的0值记录 Map<Integer, Long> monthParticipantMap = getMonthParticipantMap(participantAggResults); YearMonth thisMonth = YearMonth.now(); // 将formatter提到循环外,避免重复实例化 DateTimeFormatter monthYearFormatter = DateTimeFormatter.ofPattern("yyyyMM"); // 补全缺失月份的0值数据到map for (int i = 0; i < 12; i++) { Integer monthKey = Integer.parseInt(thisMonth.minusMonths(i).format(monthYearFormatter)); if (!monthParticipantMap.containsKey(monthKey)) { monthParticipantMap.put(monthKey, 0L); } } // 直接从补全后的map构造12条Participant记录,按月份升序排序 List<Participant> participants = monthParticipantMap.entrySet() .stream() .map(entry -> new Participant(entry.getKey(), entry.getValue())) .sorted(Comparator.comparing(Participant::getMonthKey)) .collect(Collectors.toList()); return ParticipantReportDto.builder() .participants(participants) .build(); }
如果需要按时间倒序(最新月份在前)展示,把排序规则改成.sorted(Comparator.comparing(Participant::getMonthKey).reversed())即可。
内容的提问来源于stack exchange,提问作者Akhila Smita
相关产品推荐
相关产品推荐

