优化下面这段代码Map<String, List<Department>> listMap = all.stream().collect(Collectors.groupingBy(Department::getBigcode)); Set<Map.Entry<String, List<Department>>> entries = listMap.entrySet(); List<DepartmentVo> departmentVoList = new ArrayList<>(); for (Map.Entry<String, List<Department>> entry : entries) { DepartmentVo departmentVo = new DepartmentVo(); //大科室编号 String bigCode = entry.getKey(); List<Department> departmentList = entry.getValue(); //大科室名称 String bigName = departmentList.get(0).getBigname(); departmentVo.setDepcode(bigCode); departmentVo.setDepname(bigName); //接下来进行子列表操作 List<DepartmentVo> childDepartmentVoList = new ArrayList<>(); for (Department childDepartment : departmentList) { DepartmentVo childDepartmentVo = new DepartmentVo(); childDepartmentVo.setDepcode(childDepartment.getDepcode()); childDepartmentVo.setDepname(childDepartment.getDepname()); childDepartmentVoList.add(childDepartmentVo); } departmentVo.setChildren(childDepartmentVoList); departmentVoList.add(departmentVo); } return departmentVoList;
时间: 2024-03-18 15:38:46 浏览: 121
可以使用Stream API的flatMap操作来简化代码,如下所示:
```
List<DepartmentVo> departmentVoList = all.stream()
.collect(Collectors.groupingBy(Department::getBigcode))
.entrySet().stream()
.map(entry -> {
DepartmentVo departmentVo = new DepartmentVo();
String bigCode = entry.getKey();
List<Department> departmentList = entry.getValue();
String bigName = departmentList.get(0).getBigname();
departmentVo.setDepcode(bigCode);
departmentVo.setDepname(bigName);
List<DepartmentVo> childDepartmentVoList = departmentList.stream()
.map(childDepartment -> {
DepartmentVo childDepartmentVo = new DepartmentVo();
childDepartmentVo.setDepcode(childDepartment.getDepcode());
childDepartmentVo.setDepname(childDepartment.getDepname());
return childDepartmentVo;
})
.collect(Collectors.toList());
departmentVo.setChildren(childDepartmentVoList);
return departmentVo;
})
.collect(Collectors.toList());
return departmentVoList;
```
使用flatMap操作可以避免使用嵌套的循环,使代码更加简洁易懂。
阅读全文