树结构转List

使用LinkedList效率更高

1、单个顶级节点

java 复制代码
public static List<CmsStudentOutline> getTreeList(CmsStudentOutline root) {

        List<CmsStudentOutline> list = new ArrayList<>();
        Queue<CmsStudentOutline> queue = new LinkedList<>();

        if (root == null) {
            return null;
        }
        root.setPid("0");
        //使用UUID也可以 root.setId(UUID.randomUUID().toString());
        root.setId(IdUtils.simpleUUID());
        queue.offer(root);//添加一个元素并返回true如果队列已满,则返回false
        while (!queue.isEmpty()) {
            CmsStudentOutline tree = queue.poll();//移除并返问队列头部的元素,如果队列为空,则返回null
            String pid = tree.getId();
            List<CmsStudentOutline> children = tree.getChildren();
            if (children != null) {
                for (CmsStudentOutline child : children) {
                    child.setPid(pid);
                    //使用UUID也可以 child.setId(UUID.randomUUID().toString());
                    child.setId(IdUtils.simpleUUID());
                    queue.offer(child);//添加一个元素并返回true,如果队列已满,则返回false
                }
            }
            CmsStudentOutline cmsStudentOutline = new CmsStudentOutline();
            cmsStudentOutline.setId(tree.getId());
            cmsStudentOutline.setPid(tree.getPid());
            cmsStudentOutline.setName(tree.getName());
            list.add(cmsStudentOutline);
        }
        return list;
    }

2、如果有多个顶级节点(循环即可)

java 复制代码
public List<CmsStudentOutline> getList(List<CmsStudentOutline> cmsStudentOutline)
    {
        List<CmsStudentOutline> list = new ArrayList<>();
        for (CmsStudentOutline studentOutline : cmsStudentOutline) {
            list.addAll(breadthFirstTree2List(studentOutline));
        }
        return list;
    }
相关推荐
Flittly10 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了10 小时前
Java 生成二维码解决方案
java·后端
人活一口气15 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP16 小时前
Vibe Coding -- 完整项目案例实操
java
荣码17 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing17 小时前
Google第三方授权登录
java·后端·程序员
明月光81817 小时前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java
考虑考虑1 天前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯1 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
青石路1 天前
记一次多JDK版本问题的排查,一坑套一坑,差点没爬上来
java