树结构转List

 使用LinkedList效率更高

 1、单个顶级节点

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、如果有多个顶级节点(循环即可)

public List<CmsStudentOutline> getList(List<CmsStudentOutline> cmsStudentOutline)
    {
        List<CmsStudentOutline> list = new ArrayList<>();
        for (CmsStudentOutline studentOutline : cmsStudentOutline) {
            list.addAll(breadthFirstTree2List(studentOutline));
        }
        return list;
    }

猜你喜欢

转载自blog.csdn.net/qq_38410795/article/details/132347741
今日推荐