//1.获取最新两期日期 List<String> lastTwoDate = industryScoreInfoRepository.getLastTwoDate(); // List<String> lastTwoDate = new ArrayList<>(); // lastTwoDate.add("2023-02-28"); // lastTwoDate.add("2023-01-31"); log.info("当前观点较上期变化日期:"+new Gson().toJson(lastTwoDate)); //2.根据日期获取数据 List<IndustryScoreInfo> industryScoreInfoByDate = industryScoreInfoRepository.getIndustryLastScoreInfos(lastTwoDate); Map<String, List<IndustryScoreInfo>> groups = industryScoreInfoByDate.stream().collect(Collectors.groupingBy(IndustryScoreInfo::getTrackDate)); // 遍历groups中的每个List<IndustryScoreInfo> List<IndustryScoreResult> industryScoreResults = new ArrayList<>(); //获取当前最新日期综合得分 List<IndustryScoreInfo> industryScoreInfos = groups.get(lastTwoDate.get(0)); //获取上一日期综合得分 List<IndustryScoreInfo> last = groups.get(lastTwoDate.get(1)); for(IndustryScoreInfo industry: industryScoreInfos){ IndustryScoreResult result = new IndustryScoreResult(); result.setTrackDate(industry.getTrackDate()); result.setTrackName(industry.getTrackName()); //当前日期观点分数 result.setComprehensiveScore(industry.getComprehensiveScore()); //对上一日期遍历获取track_name相同时,的综合得分,赋值 如果上一日期不存在,则为空串("")返回 for(IndustryScoreInfo lastIndustryScoreInfo: last){ if(result.getTrackName().equals(lastIndustryScoreInfo.getTrackName())){ result.setLastComprehensiveScore(lastIndustryScoreInfo.getComprehensiveScore()); } } industryScoreResults.add(result); } 代码优化
时间: 2024-01-11 15:03:22 浏览: 115
可以将获取最新两期日期和根据日期获取数据的部分合并成一个流水线,这样可以避免重复的遍历和循环,代码如下:
```
List<IndustryScoreResult> industryScoreResults = industryScoreInfoRepository.getLastTwoDate().stream()
.map(date -> industryScoreInfoRepository.getIndustryLastScoreInfos(date))
.collect(Collectors.groupingBy(IndustryScoreInfo::getTrackDate))
.entrySet()
.stream()
.flatMap(entry -> {
List<IndustryScoreInfo> current = entry.getValue().stream().filter(info -> info.getTrackDate().equals(entry.getKey())).collect(Collectors.toList());
List<IndustryScoreInfo> last = entry.getValue().stream().filter(info -> !info.getTrackDate().equals(entry.getKey())).collect(Collectors.toList());
return current.stream().map(industry -> {
IndustryScoreResult result = new IndustryScoreResult();
result.setTrackDate(industry.getTrackDate());
result.setTrackName(industry.getTrackName());
result.setComprehensiveScore(industry.getComprehensiveScore());
Optional<IndustryScoreInfo> lastIndustryScoreInfo = last.stream().filter(info -> info.getTrackName().equals(industry.getTrackName())).findFirst();
result.setLastComprehensiveScore(lastIndustryScoreInfo.isPresent() ? lastIndustryScoreInfo.get().getComprehensiveScore() : "");
return result;
});
})
.collect(Collectors.toList());
```
这样代码更加简洁,并且利用了流式处理的优势,使得代码更加易于维护和扩展。
阅读全文