1、样例
public class DepartmentService { public static void main(String[] args) { Map<String, Dept> deptMap = new HashMap<>(); deptMap.put("研发部", new Dept("研发部", "A公司")); deptMap.put("财务部", new Dept("财务部", "A公司")); deptMap.put("销售部", new Dept("销售部", "A公司")); deptMap.put("大数据产品线", new Dept("大数据产品线", "研发部")); deptMap.put("大数据开发工程师", new Dept("大数据开发工程师", "大数据产品线")); deptMap.put("硬件产品线", new Dept("硬件产品线", "研发部")); deptMap.put("游戏产品线", new Dept("游戏产品线", "研发部")); deptMap.put("数仓组", new Dept("数仓组", "大数据产品线")); deptMap.put("算法组", new Dept("算法组", "大数据产品线")); deptMap.put("算法工程师", new Dept("算法工程师", "算法组")); deptMap.put("模型组", new Dept("模型组", "游戏产品线")); deptMap.put("美工组", new Dept("美工组", "游戏产品线")); List<Dept> subDepts = getSubDepartments("研发部", deptMap); for (Dept dept : subDepts) { System.out.println(dept); } } /** * 递归获取子部门及其所有子级部门 * * @param deptId 当前部门ID * @return 子部门集合 */ public static List<Dept> getSubDepartments(String deptId, Map<String, Dept> deptMap) { List<Dept> subDepts = new ArrayList<>(); for (Dept dept : deptMap.values()) { if (dept.getParentDeptId().equals(deptId)) { subDepts.add(dept); // 递归调用,继续查找子部门的子部门 subDepts.addAll(getSubDepartments(dept.getDeptId(), deptMap)); } } return subDepts; } } class Dept { private String deptId; private String parentDeptId; public Dept(String deptId, String parentDeptId) { this.deptId = deptId; this.parentDeptId = parentDeptId; } public String getDeptId() { return deptId; } public String getParentDeptId() { return parentDeptId; } @Override public String toString() { return "Dept{" + "deptId='" + deptId + '\'' + ", parentDeptId='" + parentDeptId + '\'' + '}'; } }
标签:deptId,调用,String,递归,deptMap,Dept,部门,put,new From: https://www.cnblogs.com/fengbonu/p/18349618