将下面这段代码优化以下( List<TaskAward> taskAward = taskAwardService.selectTaskAwardByCode(primaryDatum.getTaskCode(), taskGroupCode); if(!CollectionUtils.isEmpty(taskAward)){ if(type.equals(CommonBusinessEnum.TaskTypeEnum.YDWZ.getValue())){ List<AwardDetails> objects = taskAward.stream() .map(award -> { AwardDetails awardDetails = new AwardDetails(); awardDetails.setAwardName(award.getName()); awardDetails.setAwardInfo(award.getInfo()); awardDetails.setAwardType(award.getAwardType()); return awardDetails; }) .collect(Collectors.toList()); valueMap.put("awardDetail", objects); }else { StringBuilder sbName = new StringBuilder(); StringBuilder sbInfo = new StringBuilder(); for (TaskAward award : taskAward) { sbName.append(award.getName()).append(","); sbInfo.append(award.getInfo()).append(","); } String awardName = sbName.deleteCharAt(sbName.length() - 1).toString(); String awardInfo = sbInfo.deleteCharAt(sbInfo.length() - 1).toString(); valueMap.put("awardType", taskAward.get(0).getAwardType()); valueMap.put("awardName", awardName); valueMap.put("awardInfo", awardInfo); } })
时间: 2023-02-06 19:18:29 浏览: 172
这段代码的目的是在根据任务编码从数据库中查询任务奖励信息并根据类型进行不同的处理。
如果可以接受的话,可以考虑将两个分支的逻辑合并起来,并使用Java 8中的流式API来简化代码。代码如下:
```
List<TaskAward> taskAward = taskAwardService.selectTaskAwardByCode(primaryDatum.getTaskCode(), taskGroupCode);
if (!CollectionUtils.isEmpty(taskAward)) {
String awardType = taskAward.get(0).getAwardType();
List<AwardDetails> objects = taskAward.stream()
.map(award -> {
AwardDetails awardDetails = new AwardDetails();
awardDetails.setAwardName(award.getName());
awardDetails.setAwardInfo(award.getInfo());
awardDetails.setAwardType(awardType);
return awardDetails;
})
.collect(Collectors.toList());
if (type.equals(CommonBusinessEnum.TaskTypeEnum.YDWZ.getValue())) {
valueMap.put("awardDetail", objects);
} else {
valueMap.put("awardType", awardType);
valueMap.put("awardName", String.join(",", objects.stream().map(AwardDetails::getAwardName).collect(Collectors.toList())));
valueMap.put("awardInfo", String.join(",", objects.stream().map(AwardDetails::getAwardInfo).collect(Collectors.toList())));
}
}
```
这样做的好处是可以将两个分支的逻辑合并到一起,避免了重复的代码,并且使用流式API可以大大简化代码。
阅读全文