DeptPO
@Data
public class DeptPO {
private Long id;
private String name;
private Long parentId;
private Integer nums;
}
DeptTree
@Data
public class DeptTree {
private Long id;
private String name;
private Integer nums;
private List<DeptTree> childList;
}
Test
public static List<DeptTree> buildTree(List<DeptPO> deptList) {
List<DeptTree> result = new ArrayList<>();
for (DeptPO dept : deptList) {
if (dept.getParentId().equals(0L)) {
result.add(recursiveChild(dept, deptList));
}
}
return result;
}
public static DeptTree recursiveChild(DeptPO dept, List<DeptPO> deptList) {
DeptTree deptTree = new DeptTree();
deptTree.setId(dept.getId());
deptTree.setName(dept.getName());
deptTree.setNums(0);
for (DeptPO son : deptList) {
if (deptTree.getId().equals(son.getParentId())) {
if (deptTree.getChildList() == null) {
deptTree.setChildList(new ArrayList<>());
}
deptTree.getChildList().add(recursiveChild(son, deptList));
}
}
if (deptTree.getChildList() != null) {
deptTree.setNums(getChildNumsTotal(deptTree.getChildList()) + dept.getNums());
} else {
deptTree.setNums(dept.getNums());
}
return deptTree;
}
public static int getChildNumsTotal(List<DeptTree> childList) {
int childNumsTotal = 0;
for (DeptTree deptTree : childList) {
childNumsTotal += deptTree.getNums();
}
return childNumsTotal;
}