前端需要在页面展示一棵完整的目录树,在这里记录一下demo
后端部门实体类

@Data
@NoArgsConstructor
@TableName("sys_dept")
public class SysDeptDo {
    private int deptId;
    private String deptName;
    private int parentId;
    @TableField(exist = false)
    private List<SysDeptDo> children;
}

构建部门目录树代码

@Service("sysDeptServiceImpl")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDeptDo> implements SysDeptService{
    @Autowired
    SysDeptMapper sysDeptMapper;
    @Override
    public List<SysDeptDo> getTree() {
        // 查询所有dept
        List<SysDeptDo> sysDeptDos = sysDeptMapper.selectList(null);
        // 根节点数量
        Integer num = sysDeptMapper.selectCount(new LambdaQueryWrapper<SysDeptDo>().isNull(SysDeptDo::getParentId));
        return buildTree(sysDeptDos,num);
    }

    public List<SysDeptDo> buildTree(List<SysDeptDo> sysDeptDos,Integer num){
        List<SysDeptDo> list = new ArrayList<>();
        List<SysDeptDo> tempList = new ArrayList<>();
        // 重复装入已经装载过子级的集合
        tempList.addAll(sysDeptDos);
        Iterator<SysDeptDo> iterator = sysDeptDos.iterator();
        while (iterator.hasNext()){
            SysDeptDo next = iterator.next();
            // 遍历集合如果parentId=当前对象id,则装入其childrenList
            List<SysDeptDo> childrenList = sysDeptDos.stream().filter(sysDeptDo -> {
                if (next.getDeptId() == sysDeptDo.getParentId()) {
                    // 将已经被装载过的对象从集合中剔除
                    tempList.remove(sysDeptDo);
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(childrenList)){
                next.setChildren(childrenList);
                list.add(next);
            }
        }
        // 判断当前集合长度是否等于根节点数量
        while (!(tempList.size() ==num)){
            // 递归装载子级
            buildTree(list,num);
        }
        return tempList;
    }
}

传递给前端的结构

java 递归 树形结构 java递归树形目录_List