java 实现部门层级树
时间: 2024-04-06 08:29:30 浏览: 103
java简单开发部门树(Tree)
要实现部门层级树,可以使用树形数据结构。以下是一个简单的 Java 实现示例:
首先,需要定义一个部门类,包含部门 ID、父部门 ID、部门名称等属性:
```
public class Department {
private int id;
private int parentId;
private String name;
// 构造方法、getter、setter 略
}
```
接下来,可以定义一个方法,接收部门列表作为参数,返回一个根据部门层级关系构建的树形结构:
```
public static List<Department> buildDepartmentTree(List<Department> departmentList) {
// 首先,将所有部门按照父部门 ID 分组
Map<Integer, List<Department>> departmentMap = departmentList.stream()
.collect(Collectors.groupingBy(Department::getParentId));
// 然后,递归构建树形结构
List<Department> rootDepartments = departmentMap.get(0);
for (Department department : rootDepartments) {
buildDepartmentTree(department, departmentMap);
}
return rootDepartments;
}
private static void buildDepartmentTree(Department department, Map<Integer, List<Department>> departmentMap) {
List<Department> subDepartments = departmentMap.get(department.getId());
if (subDepartments != null) {
department.setSubDepartments(subDepartments);
for (Department subDepartment : subDepartments) {
buildDepartmentTree(subDepartment, departmentMap);
}
}
}
```
上述代码中,首先将所有部门按照父部门 ID 分组,然后从根节点开始递归构建树形结构,直到所有节点都被加入到树中。
最后,可以通过递归遍历树形结构,将部门层级树打印出来:
```
public static void printDepartmentTree(List<Department> departmentList, int level) {
if (departmentList == null || departmentList.isEmpty()) {
return;
}
for (Department department : departmentList) {
System.out.println(String.join("", Collections.nCopies(level, "-"))
+ department.getName() + " (" + department.getId() + ")");
printDepartmentTree(department.getSubDepartments(), level + 1);
}
}
```
这样,就可以通过以下代码来构建和打印部门层级树:
```
List<Department> departmentList = Arrays.asList(
new Department(1, 0, "总公司"),
new Department(2, 1, "财务部"),
new Department(3, 1, "人力资源部"),
new Department(4, 2, "财务一部"),
new Department(5, 2, "财务二部"),
new Department(6, 3, "招聘组"),
new Department(7, 3, "培训组")
);
List<Department> departmentTree = buildDepartmentTree(departmentList);
printDepartmentTree(departmentTree, 0);
```
输出结果如下:
```
总公司 (1)
-财务部 (2)
--财务一部 (4)
--财务二部 (5)
-人力资源部 (3)
--招聘组 (6)
--培训组 (7)
```
阅读全文