java cte查询出tree的List转化为 tree的代码

/**
     * List树 -> 树
     * 核心
     * ************
     * 将数组型的JsonObjects转成树状结构
     * 注意,一定要排好顺序那种
     * 应用: cte语法查询出父级子级的list,想转化成树
     *
     * @param nodes    数据源
     * @param parentId 顶级的id(就是最顶层的parentId)
     * @return
     */
    public static JsonObjects toTree(JsonObjects nodes, Long parentId) {
        //创建临时组装存储空间
        JsonObjects result = JsonObjects.VOID();
        //如果存在原-List
        if (CollectionUtils.isNotEmpty(nodes)) {
            //如果不存在,给与默认值
            if (parentId == null) {
                parentId = nodes.get(0).getLong("parentId", 0);
            }
            //for循环
            for (JsonObject node : nodes) {
                //获取原-list中的parentId
                long thisParentId = node.getLong("parentId");
                //对比父级id
                if (thisParentId == parentId) {
                    //递归
                    JsonObjects children = toTree(nodes, node.getLong("id"));
                    //如果存在数据,组装上
                    if (CollectionUtils.isNotEmpty(children)) {
                        node.append("children", children);
                    }
                    //验证是否存在
                    if (!result.contains(node)) {
                        //不存在,存入
                        result.add(node);
                    }
                }
            }
        }
        return result;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章