java 递归得到部门树

该博客介绍了一种使用Java递归方法来构建包含部门及其子部门和人员的树形结构。通过调用`getTree`方法,从数据库获取部门数据,并通过`recursion`函数递归地填充子部门和员工信息。最后,`getChildList`方法用于筛选出给定父部门的子部门。整个过程确保了部门下所有人员数量的准确计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java代码  收藏代码
  1. public DepartmentUserTreeNode getTree(String location,String  name) {  
  2.         List<DepartmentUserTreeNode> depts = deparDao.qryDepts();  
  3.         DepartmentUserTreeNode rootDept = deparDao.qryRootDept();  
  4.           
  5.           
  6.         recursion(depts, rootDept,0,location,name);  
  7.           
  8.         return rootDept;  
  9.           
  10.     }  
  11.       
  12.       
  13.     private int recursion(List<DepartmentUserTreeNode> list, DepartmentUserTreeNode node,int count,String location,String  name) {  
  14.         List<DepartmentUserTreeNode> childList = getChildList(list, node);// 得到子节点列表  
  15.         List<Employee> emps = empDao.qryByDept(node.getDeptId(),location,name);  
  16.         count = CollectionUtils.isEmpty(emps)?0:emps.size();  
  17.           
  18.           
  19.         node.setEmps(emps);  
  20.         
  21.         if (!CollectionUtils.isEmpty(childList)) {  
  22.             
  23.            node.setDepts(childList);  
  24.            
  25.             Iterator<DepartmentUserTreeNode> it = childList.iterator();  
  26.             while (it.hasNext()) {  
  27.                 DepartmentUserTreeNode n = (DepartmentUserTreeNode) it.next();  
  28.                 count = count+recursion(list, n,count,location,name);  
  29.             }  
  30.               
  31.         } else {  
  32.             node.setDepts(null);  
  33.         }  
  34.           
  35.         node.setEmpCount(count);  
  36.         return count;  
  37.     }  
  38.       
  39.     private List<DepartmentUserTreeNode> getChildList(List<DepartmentUserTreeNode> list, DepartmentUserTreeNode node) {  
  40.         List<DepartmentUserTreeNode> nodeList = new ArrayList<DepartmentUserTreeNode>();  
  41.         Iterator<DepartmentUserTreeNode> it = list.iterator();  
  42.         while (it.hasNext()) {  
  43.             DepartmentUserTreeNode n = (DepartmentUserTreeNode) it.next();  
  44.             if (n.getParentId().equals(node.getDeptId()) ) {  
  45.                 nodeList.add(n);  
  46.             }  
  47.         }  
  48.         return nodeList;  
  49.     }  

输入,LIST数据

JAVA递归 ,得到部门树,部门人员,以及,当前部门下所有的人员数(一直到底)。

 

结果数据格式:

 

最终展现:


/** * 根据等级查询类目 * * @param level * @return */ @Override public List queryCategoryTree(Integer level) { //查询当前级别下类目 List list = categoryDAO.list(level); //组装好的类目,返回前端 List categoryTree = new ArrayList(); //所有类目 List allDTOList = new ArrayList(); if (CollectionUtils.isEmpty(list)) { return categoryTree; } for (CategoryDO categoryDO : list) { allDTOList.add(new CategoryTreeDTO().convertDOToDTO(categoryDO)); } //当前等级类目 categoryTree = allDTOList.stream().filter(dto -> level.equals(dto.getLevel())).collect(Collectors.toList()); for (CategoryTreeDTO categoryTreeDTO : categoryTree) { //组装类目为结构 assembleTree(categoryTreeDTO, allDTOList,Constants.CATEGORY_MAX_LEVEL - level); } return categoryTree; } /** * 组装 * * @param categoryTreeDTO * @param allList * @param remainRecursionCount 剩余递归次数 * @return */ public CategoryTreeDTO assembleTree(CategoryTreeDTO categoryTreeDTO, List allList, int remainRecursionCount) { remainRecursionCount--; //最大递归次数不超过Constants.CATEGORY_MAX_LEVEL-level次,防止坏数据死循环 if(remainRecursionCount < 0){ return categoryTreeDTO; } String categoryCode = categoryTreeDTO.getCategoryCode(); Integer level = categoryTreeDTO.getLevel(); //到达最后等级返回 if (Constants.CATEGORY_MAX_LEVEL == level) { return categoryTreeDTO; } //子类目 List child = allList.stream().filter(a -> categoryCode.equals(a.getParentCode())).collect(Collectors.toList()); if (null == child) { return categoryTreeDTO; } categoryTreeDTO.setChildren(child); //组装子类目 for (CategoryTreeDTO dto : child) { assembleTree(dto, allList,remainRecursionCount); } return categoryTreeDTO; }
### Java实现部门人员组织结构Java中构建部门人员树形结构通常涉及多个层次的数据处理。以下是基于提供的引用内容以及常见的开发实践来描述如何实现这一功能。 #### 数据模型设计 为了表示部门及其下属成员的关系,可以定义类似于`DeptTreeDto`、`Node`或`TreeDept`这样的实体类。这些类的核心属性包括: - `id`: 唯一标识符。 - `pId` 或 `pid`: 父节点ID,用于建立父子关系。 - `name`: 节点名称(部门名或用户名)。 - `type`: 节点类型(如部门还是用户)。 - `children`: 保存子节点列表。 以下是一个综合性的数据模型示例[^1]: ```java @Data public class DepartmentUserTreeNode { private Long id; private Long parentId; // 父级ID private String name; private Integer type; // 0: 部门, 1: 用户 private List<DepartmentUserTreeNode> children; public DepartmentUserTreeNode(Long id, Long parentId, String name, Integer type) { this.id = id; this.parentId = parentId; this.name = name; this.type = type; } } ``` --- #### 构建的方法 通过递归或者迭代的方式可以从扁平化的数据集中生成树形结构。假设有一个包含所有节点的集合,则可以通过如下方法完成转换: ```java import java.util.*; import java.util.stream.Collectors; public class TreeBuilder { /** * 将节点列表转化为树形结构 * * @param nodes 所有节点组成的列表 * @return 根节点列表 */ public static List<DepartmentUserTreeNode> buildTree(List<DepartmentUserTreeNode> nodes) { Map<Long, DepartmentUserTreeNode> nodeMap = new HashMap<>(); // 创建哈希映射以便快速访问每个节点 for (DepartmentUserTreeNode node : nodes) { node.setChildren(new ArrayList<>()); // 初始化子节点容器 nodeMap.put(node.getId(), node); } List<DepartmentUserTreeNode> rootNodes = new ArrayList<>(); // 连接父节点与子节点 for (DepartmentUserTreeNode node : nodes) { if (node.getParentId() != null && nodeMap.containsKey(node.getParentId())) { DepartmentUserTreeNode parentNode = nodeMap.get(node.getParentId()); parentNode.getChildren().add(node); } else { // 如果没有父节点则认为是根节点 rootNodes.add(node); } } return rootNodes; } } ``` 此代码片段展示了如何利用`buildTree()`函数将一组无序的节点构建成具有层级关系的状对象[^2]。 --- #### 查询数据库中的数据 实际项目中可能需要从数据库读取原始记录再加工成所需的格式。SQL查询语句可以根据具体需求定制。例如下面这段SQL用来提取某个特定部门下的所有员工信息[^4]: ```sql SELECT d.id AS dept_id, d.c_name AS dept_name, u.id AS user_id, u.c_name AS user_name FROM departments d LEFT JOIN users u ON d.id = u.department_id WHERE d.id IN ( SELECT DISTINCT department_id FROM employees WHERE status='active' ) ORDER BY d.id ASC; ``` 执行该脚本后会得到一张二维表格形式的结果集,其中每一行代表一条独立的信息条目——要么属于某一层级上的部门单元,要么关联至具体的个人资料项。 --- #### 展示前端界面 最后,在客户端渲染部分可选用各种框架库比如Vue.js配合Element UI组件插件绘制可视化的图表效果。这里仅提供伪代码示意逻辑流程: ```javascript // Vue Component Example export default { data() { return { treeData: [] // 后端返回的JSON数组 }; }, methods: { loadTreeStructure(responseBody){ this.treeData = responseBody.map(item => ({ ...item, label: item.type === 'DEPT' ? item.deptName : `${item.userName}(${item.userId})`, children: Array.isArray(item.children)? [...item.children].map(child=>({...child})):[] })); } } }; ``` 以上就是关于使用Java技术栈搭建企业内部管理系统里涉及到的部门架构图的相关知识点介绍[^3]. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值