Erlo

组织树查询-Jvava实现(递归)

2023-04-19 14:30:54 发布   51 浏览  
页面报错/反馈
收藏 点赞

1.首先查询出组织机构

就是一个简单的查询

List deptList = mapper.getDeptList();
        Map nodeMap = new HashMap();
        List rootIds = new ArrayList();
        for (Dept dept : deptList) {
            Long deptId = dept.getDeptId();
            String name = dept.getDeptName();
            Long parentId = dept.getParentId();
            OrgNode node = nodeMap.computeIfAbsent(deptId, OrgNode::new);
            node.setId(deptId);
            node.setLabel(name);
            node.setParentId(parentId);

            if (parentId == 0) {
                rootIds.add(deptId);
            } else {
                OrgNode parent = nodeMap.computeIfAbsent(parentId, OrgNode::new);
                parent.getChildren().add(node);
            }
        }
        // 3. 输出组织机构
        List orgList = new ArrayList();
        for (long rootId : rootIds) {
            orgList.add(nodeMap.get(rootId));
        }
        List> result = dfs2(orgList);

2.def2方法,只查询两级

业务需要

/**
     * 只查询两级
     * @param nodes
     * @return
     */
    private static List> dfs2(List nodes) {
        List> result = new ArrayList();
        for (OrgNode node : nodes) {
            Map map = new HashMap();
            map.put("id", node.getId());
            map.put("label", node.getLabel());
            map.put("parentId", node.getParentId());
            List children = node.getChildren();
            if (children != null && !children.isEmpty()){
                List collect = children.stream().peek(s -> s.setChildren(null)).collect(Collectors.toList());
                map.put("children", collect);
            }
            result.add(map);
        }
        return result;
    }

效果

查询所有级别递归查询


/**
     * 查询所有组织树
     * @param nodes
     * @return
     */
    private static List> dfs(List nodes) {
        List> result = new ArrayList();
        for (OrgNode node : nodes) {
            Map map = new HashMap();
            map.put("id", node.getId());
            map.put("label", node.getLabel());
            map.put("parentId", node.getParentId());
            List children = node.getChildren();
            if (children != null && !children.isEmpty()) {
                map.put("children", dfs(children));
            }
            result.add(map);
        }
        return result;
    }

3.前端代码




    
    树形控件
    
    
    
    


通过 node 获取

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认