优化代码 List<JourneyGroup> groups = groupRepository.getGroupListByOrder(companyId, orderField,orderType); for (JourneyGroup group : groups) { Map<String,Object> groupMap = Maps.newHashMap(); groupMap.put("id",group.getId()); //判断是否为默认分组,1为默认分组 if (group.getDefaultGroup() != null && group.getDefaultGroup() == 1) { groupMap.put("name",MessageLocalHelper.getMessage("journey.base.default") ); }else if(group.getParentId()!=null&&group.getParentId()==0L){ groupMap.put("name",MessageLocalHelper.getMessage("all.grouping") ); } else { groupMap.put("name",group.getName()); } groupMap.put("default", group.getDefaultGroup()); groupMap.put("parentId",group.getParentId()); Integer count = journeyGroupMiddleRepository.countALLJourneyGroupMiddleByGroupId(group.getId()); groupMap.put("count",count); list.add(groupMap); }
时间: 2024-01-01 13:05:41 浏览: 78
可以考虑使用流式编程,减少循环中的临时变量。代码优化如下:
```
List<Map<String,Object>> list = groupRepository.getGroupListByOrder(companyId, orderField, orderType).stream()
.map(group -> {
Map<String,Object> groupMap = new HashMap<>();
groupMap.put("id", group.getId());
if (group.getDefaultGroup() != null && group.getDefaultGroup() == 1) {
groupMap.put("name", MessageLocalHelper.getMessage("journey.base.default"));
} else if (group.getParentId() != null && group.getParentId() == 0L) {
groupMap.put("name", MessageLocalHelper.getMessage("all.grouping"));
} else {
groupMap.put("name", group.getName());
}
groupMap.put("default", group.getDefaultGroup());
groupMap.put("parentId", group.getParentId());
groupMap.put("count", journeyGroupMiddleRepository.countALLJourneyGroupMiddleByGroupId(group.getId()));
return groupMap;
}).collect(Collectors.toList());
```
此外,如果 `groupRepository.getGroupListByOrder()` 和 `journeyGroupMiddleRepository.countALLJourneyGroupMiddleByGroupId()` 的查询语句较为复杂,可以尝试进行 SQL 优化,或者使用缓存来提高查询效率。
阅读全文