场景:
list列表中数据如下图所示,有很多属性相同的数据,现在需要将这些数据分组
解决方案:
Map<String, List<RiskAssessForTrendVo>> assessResultMap =
assessResultList.stream()
.collect(Collectors.groupingBy(RiskAssessForTrendVo::getCreateTime));
解释:
//(第一个*表示实体类,第二个*表示实体类中属性,如果不是实体类,可直接写)
Map< x,x > Map = list.stream().collect(groupingBy(*::get*));
分组后数据如下
之后可以对分组后的map进行遍历
for (Map.Entry<String, List<RiskAssessForTrendVo>> entry : assessResultMap.entrySet()) {
//key是分组的日期 value是List<RiskAssessForTrendVo>
String createTime = entry.getKey();
double totalScoreAll = 0;
List<RiskAssessForTrendVo> riskAssessRecordList = assessResultMap.get(createTime);
if (CollectionUtil.isNotEmpty(riskAssessRecordList)) {
for (RiskAssessForTrendVo riskAssessRecord : riskAssessRecordList) {
double totalScore = riskAssessRecord.getTotalScore();
totalScoreAll += totalScore;
}
SynthesizeSafeTrendVo safeTrendVo = new SynthesizeSafeTrendVo();
safeTrendVo.setScore(Math.rint(totalScoreAll / riskAssessRecordList.size()));
safeTrendVo.setTime(createTime);
trendList.add(safeTrendVo);
}
}