java 文章目录递归(一级标题,二级标题)
1、表现样式
2、废话不多说,直接上代码
Dept{
private int id;
private String name;
private int pid;
private int orderId;
}
DeptLevelVo{
private int id;
private String name;
private int pid;
private List<DeptLevelVo> Children;
}
public ServerResponse<List<DeptLevelVo>> getDeptTree() {
List<Dept> depts = deptMapper.findAll();
List<DeptLevelVo> deptVos = new ArrayList<DeptLevelVo>();
for (Dept dept : depts) {
DeptLevelVo deptLevelVo = DeptLevelVo.builder().id(dept.getId())
.deptName(dept.getName()).empNum(dept.getDeptNum())
.sequence(dept.getSeq()).parentId(dept.getParentId()).build();
deptVos.add(deptLevelVo);
}
return ServerResponse.success(tease(deptVos));
}
private List<DeptLevelVo> tease(List<DeptLevelVo> deptVos){
List<DeptLevelVo> rootList = new ArrayList<DeptLevelVo>();
Multimap<Integer,DeptLevelVo> container = ArrayListMultimap.create();
for (DeptLevelVo deptVo : deptVos){
if(deptVo.getParentId() == 0){
rootList.add(deptVo);
}
container.put(deptVo.getParentId(),deptVo);
}
Collections.sort(rootList, new Comparator<DeptLevelVo>() {
public int compare(DeptLevelVo o1, DeptLevelVo o2) {
return 1;
}
});
hierachy(rootList,container);
return rootList;
}
private void hierachy(List<DeptLevelVo> deptVos, Multimap container) {
for (DeptLevelVo deptVo : deptVos) {
List<DeptLevelVo> deptChilds = (List<DeptLevelVo>) container.get(deptVo.getId());
deptVo.setDeptChild(deptChilds);
Collections.sort(deptChilds, new Comparator<DeptLevelVo>() {
public int compare(DeptLevelVo o1, DeptLevelVo o2) {
return 1;
}
});
hierachy(deptChilds,container);
}
}
特别说明:
Multimap 包引用:
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;