美文网首页
Java 递归生成层级树(通用)

Java 递归生成层级树(通用)

作者: 王疏蔬 | 来源:发表于2020-09-29 17:20 被阅读0次

通用于菜单树、机构树、组织树等

    /**
     * 返回层级结构树
     */
    public List<实体> getStructure() {
        //查询所有数据
        List<实体> allList = mapper.selectAll();
        //查询顶级数据
        List<实体> topList = mapper.getTop();
        //为一级数据设置子数据,getChild是递归调用的
        if (!CollectionUtils.isEmpty(topList)) { //不为空进入
            for (实体 entity : topList) {
                //需在实体创建存放结构树字段进行set
                entity.setHierarchy(getChild(entity.getId(), allList));
            }
        }
        return topList;
    }
 /**
 * 调用递归
 */
private List<实体> getChild(String id, List<实体> allList) {
    // 子级数据
    List<实体> childList = Lists.newArrayList();
    for (实体 entity : allList) {
        // 遍历所有节点,将父菜单id与传过来的id比较
        if (StringUtils.isNotBlank(entity.getParentId())) {
            if (entity.getParentId().equals(id)) {
                childList.add(entity);
            }
        }
    }
    // 把子级数据的子级再循环一遍
    for (实体 entity : childList) {
        if (StringUtils.isNotBlank(entity.getParentId())) {
            // 递归
            entity.setHierarchy(getChild(entity.getId(), allList));
        }
    }
    // 递归退出条件
    if (childList.size() == 0) {
        return null;
    }
    return childList;
}

相关文章

网友评论

      本文标题:Java 递归生成层级树(通用)

      本文链接:https://www.haomeiwen.com/subject/agveuktx.html