业务场景:
从数据库查询出的数组(户主和户成员在前一起)根据一个户主证件号码分组之后,对户成员进行数据拼装,最后再把数据更新到目标表中。
第一步:根据条件查询数组;
List<UpdateMonitorVo> listIdCard = updateMonitorMapper.listIdCard();第二步:根据户主证件号码进行分组;
Map<String, List<UpdateMonitorVo>> companyVehicles = listIdCard.stream().collect(Collectors.groupingBy(UpdateMonitorVo::getHuZhuIdCard)); Set<Map.Entry<String, List<UpdateMonitorVo>>> entries4 = companyVehicles.entrySet();第三步:数据拼装并更新目标表
for (Map.Entry<String, List<UpdateMonitorVo>> stringListEntry : entries4) { String key = stringListEntry.getKey().substring(1); String problemDesc = ""; List<UpdateMonitorVo> list = stringListEntry.getValue(); for (UpdateMonitorVo vo : list) { problemDesc = "姓名:" + vo.getName() + ",证件号码:" + vo.getIdCard() + ",与户主关系:" + vo.getRelation() + ",民族:" + vo.getNation() + ",文化程度:" + (StringUtils.isNotBlank(vo.getEducation()) ? vo.getEducation() : "") + ",在校生状况:" + (StringUtils.isNotBlank(vo.getZxs()) ? vo.getZxs() : "") + ",健康状况:" + vo.getHealth() + ",劳动技能:" + vo.getLaborSkill() + ",务工时间(月):" + vo.getLaborMonth() + ",脱贫状态:" + vo.getMark() + "。"; } updateMonitorMapper.updateDataByIdCard(key, problemDesc); } public void updateMonitorData() { List<UpdateMonitorVo> listIdCard = updateMonitorMapper.listIdCard(); Map<String, List<UpdateMonitorVo>> companyVehicles = listIdCard.stream().collect(Collectors.groupingBy(UpdateMonitorVo::getHuZhuIdCard)); Set<Map.Entry<String, List<UpdateMonitorVo>>> entries4 = companyVehicles.entrySet(); for (Map.Entry<String, List<UpdateMonitorVo>> stringListEntry : entries4) { String key = stringListEntry.getKey().substring(1); String problemDesc = ""; List<UpdateMonitorVo> list = stringListEntry.getValue(); for (UpdateMonitorVo vo : list) { problemDesc = "姓名:" + vo.getName() + ",证件号码:" + vo.getIdCard() + ",与户主关系:" + vo.getRelation() + ",民族:" + vo.getNation() + ",文化程度:" + (StringUtils.isNotBlank(vo.getEducation()) ? vo.getEducation() : "") + ",在校生状况:" + (StringUtils.isNotBlank(vo.getZxs()) ? vo.getZxs() : "") + ",健康状况:" + vo.getHealth() + ",劳动技能:" + vo.getLaborSkill() + ",务工时间(月):" + vo.getLaborMonth() + ",脱贫状态:" + vo.getMark() + "。"; } updateMonitorMapper.updateDataByIdCard(key, problemDesc); } }总结:java 8新特性把stream流分组,避免多次和数据库交互和很多的垃圾代码,使代码更简洁易读。