递归获取某个节点的儿子节点

java 代码:

public List<Department> getAllChildrenDepartmentsFlat(Long parentId) {
        List<Department> allDepartments = departmentRepository.findAll();  // 假设使用JPA的Repository来进行数据库操作

        List<Department> allChildren = new ArrayList<>();
        Department parent = departmentRepository.findById(parentId);
        if (parent != null) {
            allChildren.add(parent);
            flattenChildren(allDepartments, parent, allChildren);
        }

        return allChildren;
    }

    private void flattenChildren(List<Department> allDepartments, Department parent, List<Department> flatList) {
        List<Department> children = allDepartments.stream()
                .filter(department -> department.getParentId().equals(parent.getId()))
                .collect(Collectors.toList());
        
        for (Department child : children) {
            flatList.add(child);
            flattenChildren(allDepartments, child, flatList);
        }
    }

  

posted @ 2024-04-19 11:18  翱翔的小鱼  阅读(12)  评论(0编辑  收藏  举报