树结构封装

public class TreeNode<T> {

    @Schema(description = "id")
    private String            id;

    @Schema(description = "名称")
    private String            name;

    @Schema(description = "父级id")
    private String            parentId;

    @Schema(description = "排序")
    private Integer           sort;

    @Schema(description = "类型")
    private String            type;

    @Schema(description = "别名")
    private String            alias;

    @Schema(description = "子集")
    private List<TreeNode<T>> children;

    @Schema(description = "扩展字段")
    private T                 ext;

    @Schema(description = "扩展数据集")
    private Object            extra;

}
public class TreeBuild<T> {

    private final String      rootParentId = "0";

    private List<TreeNode<T>> nodeList     = new ArrayList<>();

    public TreeBuild(List<TreeNode<T>> nodeList) {
        this.nodeList = nodeList;
    }

    private TreeBuild() {
    }

    /**
     * 构建
     * @return  /
     */
    public List<TreeNode<T>> build() {
        List<TreeNode<T>> treeNodes = new ArrayList<>();
        getRootNode().forEach(root -> {
            treeNodes.add(buildChildTree(root));
        });
        return treeNodes;
    }

    /**
     * 获取根节点
     * @return  /
     */
    private List<TreeNode<T>> getRootNode() {
        List<TreeNode<T>> rootNodeList = new ArrayList<>();
        nodeList.forEach(item -> {
            if (rootParentId.equals(item.getParentId())) {
                rootNodeList.add(item);
            }
        });
        return rootNodeList;
    }

    /**
     * 处理子集
     * @param parentNode /
     * @return /
     */
    private TreeNode<T> buildChildTree(TreeNode<T> parentNode) {
        List<TreeNode<T>> childTree = new ArrayList<>();
        nodeList.forEach(item -> {
            // 如果相等便进入 处理子集的数据,子集如果还有就处理子集的子集,由里向外设置数据
            if (parentNode.getId().equals(item.getParentId())) {
                childTree.add(buildChildTree(item));
            }
        });
        parentNode.setChildren(childTree);
        return parentNode;
    }

}

使用

List<TreeNode<String>> funAuthResults = baseMapper.funAuthList(hosId, areaId);
        TreeBuild<String> treeBuild = new TreeBuild<>(funAuthResults);
        List<TreeNode<String>> treeNodes = treeBuild.build();

你可能感兴趣的:(java排坑之路,java,spring,spring,boot)