java中树结构的基本实现(layui树结构保存权限示例)

1:创建树节点基本类

@Data
@AllArgsConstructor
@NoArgsConstructor
class TreeNode {
    private int id;
    private int parentId;

    private String title;
    private List<TreeNode> children;

    //是否选中
    private boolean checked;
    //是否禁用
    private boolean disabled;

    /**
     * 校验是否是顶级节点
     */
    public boolean isRootNode() {
        return parentId == 0;
    }
}

2:构建树结构工具类

class BuildTreeUtils {
    private List<TreeNode> treeNodes;

    public BuildTreeUtils(List<TreeNode> treeNodes) {
        this.treeNodes = treeNodes;
    }

    public List<TreeNode> buildTree() {
        List<TreeNode> tree = new ArrayList<>();
        //获取顶级树集合
        List<TreeNode> rootTreeNodes = this.treeNodes.stream().filter(t -> t.isRootNode()).collect(Collectors.toList());

        //遍历顶级树集合,并构建子结构
        for (TreeNode t : rootTreeNodes) {
            t = buildSonTree(t);
            tree.add(t);
        }
        return tree;
    }


    private TreeNode buildSonTree(TreeNode t) {
        //1:创建子结构的集合
        List<TreeNode> sonList = new ArrayList<>();
        //2:遍历全部的树节点,找到父节点为当前节点id的。并且设置的时候 直接调用当前方法继续构建子集
        for (TreeNode allNode : treeNodes) {
            if (t.getId() == allNode.getParentId()) {
                sonList.add(buildSonTree(allNode));
            }
        }
        //3:把子结构设置到当前node的子属性上
        t.setChildren(sonList);
        return t;
    }
}

3:创建数据测试

public static void main(String[] args) {
        List<TreeNode> treeNodes = Arrays.asList(
                new TreeNode(1, 0, "节点1", null, false, false),
                new TreeNode(2, 0, "节点2", null, false, false),

                new TreeNode(3, 1, "节点3", null, false, false),
                new TreeNode(4, 2, "节点4", null, false, false),

                new TreeNode(5, 3, "节点5", null, false, false),
                new TreeNode(6, 4, "节点6", null, false, false)
        );

        BuildTreeUtils utils = new BuildTreeUtils(treeNodes);
        List<TreeNode> tree = utils.buildTree();
        System.out.println(JSON.toJSONString(tree));
    }

结果如下

[
    {
        "checked":false,
        "children":[
            {
                "checked":false,
                "children":[
                    {
                        "checked":false,
                        "children":[

                        ],
                        "disabled":false,
                        "id":5,
                        "parentId":3,
                        "rootNode":false,
                        "title":"节点5"
                    }
                ],
                "disabled":false,
                "id":3,
                "parentId":1,
                "rootNode":false,
                "title":"节点3"
            }
        ],
        "disabled":false,
        "id":1,
        "parentId":0,
        "rootNode":true,
        "title":"节点1"
    },
    {
        "checked":false,
        "children":[
            {
                "checked":false,
                "children":[
                    {
                        "checked":false,
                        "children":[

                        ],
                        "disabled":false,
                        "id":6,
                        "parentId":4,
                        "rootNode":false,
                        "title":"节点6"
                    }
                ],
                "disabled":false,
                "id":4,
                "parentId":2,
                "rootNode":false,
                "title":"节点4"
            }
        ],
        "disabled":false,
        "id":2,
        "parentId":0,
        "rootNode":true,
        "title":"节点2"
    }
]

 

下面是一个layui获取选中的树节点案例

<div id="auth-tree"></div>
<div class="layui-form-item">
    <div class="layui-input-block">
        <button type="submit" id="save-auth" class="layui-btn" lay-submit>提交</button>
    </div>
</div>
layui.use(['tree'], function () {
    let tree = layui.tree;

    let roleId = getUrlParam("roleId");
    $.get("/user/queryAuthTree?roleId=" + roleId, function (data) {
        tree.render({
            id: 'AUTH_TREE_ID',
            elem: '#auth-tree',
            data: data,
            showCheckbox: true,
            disable: true
        });
    });

    $("#save-auth").click(function (){
        //获取数据 是一个树结构,需要遍历拿到所有的id集合
        let data = tree.getChecked("AUTH_TREE_ID");
        let authIds = getSonTree(data);
        $.ajax({
            type: "post",
            url: "/user/saveAuth",
            data: {"roleId": roleId, "authList": authIds.join(",")},
            success: function (data) {
                if (data.code === 202 || data.code === 0) {
                    layer.msg(data.msg, {icon: 1});
                    closePage();
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            },
            error: function (err) {
                layer.msg(err.responseText ? err.responseText : '无权限或操作失败!', {icon: 2});
            }
        })
    })
    function closePage() {
        setTimeout(function () {
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        }, 1000)
    }
    //获取树的子集
    function getSonTree(data){
        let authIds = new Array();
        if(data){
            for (let i = 0; i < data.length; i++) {
                //把当前的id保存
                authIds.push(data[i].id);
                if(data[i].children){
                    //递归返回子元素的数据
                    let sonTree = getSonTree(data[i].children);
                    //合并两个数组
                    authIds = $.merge(authIds,sonTree);
                }
            }
        }

        return authIds;
    }
});

 

posted @ 2023-08-24 10:54  鸭猪是的念来过倒  阅读(119)  评论(0编辑  收藏  举报