67,550
社区成员




public class Sample {
public static class Dept {
private Integer id;
private String deptName;
private List<Dept> deptList;
public Integer getId() {return id;}
public String getDeptName( ) {return deptName;}
public List<Dept> getDeptList() {return deptList;}
public void setId(Integer id) {this.id = id;}
public void setDeptName(String deptName) {this.deptName = deptName;}
public void setDeptList(List<Dept> deptList) {this.deptList = deptList;}
public String toString() {return String.format("id=%s, deptName=%s, deptList=[%s]", id, deptName, deptList);}
}
// 测试数据(一共3层,每层2个子部门)
public static Dept generateSampleDept(int id, int deep) {
Dept dept = new Dept();
dept.setId(id);
dept.setDeptName(String.format("部门%d", id));
dept.setDeptList(new ArrayList<>());
if (deep < 3) {
for (int i=1; i<3; i++) {
dept.getDeptList().add(generateSampleDept(id*10 + i, deep+1));
}
}
return dept;
}
// 查询部门
public static Dept searchDept(Dept dept, int id) {
Dept result = null;;
if (dept.getId().equals(id)) {
return dept;
}
for (Dept sub : dept.getDeptList()) {
result = searchDept(sub, id);
}
return result;
}
// 递归获取所有部门
public static List<Dept> getAllDept(Dept dept) {
List<Dept> list = new ArrayList<>();
list.add(dept);
for (Dept sub : dept.getDeptList()) {
list.addAll(getAllDept(sub));
}
return list;
}
public static void main(String[] args) {
try {
Dept dept = generateSampleDept(0, 0); //测试数据
System.out.println(dept); //打印所有部门
Dept father = searchDept(dept, 22); //查找父部门
if (father != null) {
List<Dept> allDept = getAllDept(father); //递归获得所有部门
System.out.printf("一共有%d个部门\n", allDept.size()); //确认一共有几个部门
for (Dept sub : allDept) {
System.out.println(sub);
}
List<Integer> allId = allDept.stream().map(e->e.getId()).collect(Collectors.toList()); //获得所有部门的id
System.out.println(allId);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}