使用Java取出末级部门
时间: 2024-04-20 21:04:48 浏览: 54
假设我们有一个Department类,其中包含id和parentId属性,parentId为0表示该部门为顶级部门。
我们可以通过递归的方式,从顶级部门开始遍历整个部门树,找到所有末级部门:
```java
public List<Department> getLeafDepartments(List<Department> departments, int parentId) {
List<Department> result = new ArrayList<>();
for (Department department : departments) {
if (department.getParentId() == parentId) {
List<Department> children = getLeafDepartments(departments, department.getId());
if (children.isEmpty()) {
result.add(department);
} else {
result.addAll(children);
}
}
}
return result;
}
```
我们可以将所有部门存储在一个列表中,然后调用该方法来获取所有末级部门。例如:
```java
List<Department> departments = new ArrayList<>();
// 添加部门数据
List<Department> leafDepartments = getLeafDepartments(departments, 0);
// 输出所有末级部门
for (Department department : leafDepartments) {
System.out.println(department.getId());
}
```
阅读全文