一、基本模型

@Data
public class ResourceTreeVO {
   

    private Long resourceId;
    /** * 资源级别 * 1:一级,2:二级,3:三级 */
    private Integer level;
    /** * 资源名称 */
    private String name;
    /** * 父级ID */
    private Long parentId;
    /** * 权限标识 */
    private String code;
    /** * 子列表 */
    private List<ResourceTreeVO> children;


    public ResourceTreeVO(Resource resource) {
   
        this.resourceId = resource.getResourceId();
        this.level = resource.getLevel();
        this.name = resource.getName();
        this.parentId = resource.getParentId();
        this.code = resource.getCode();
        this.children = null;
    }

    public ResourceTreeVO() {
   
    }
}

如何基于这个Model数据,构建树?

二、递归工具类

public class ResourceTreeUtil {
   
    private List<ResourceTreeVO> rootList; //根节点对象存放到这里
    private List<ResourceTreeVO> bodyList; //其他节点存放到这里
    public ResourceTreeUtil(List<ResourceTreeVO> rootList, List<ResourceTreeVO> bodyList) {
   
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    // 构建Tree方法调用
    public List<ResourceTreeVO> getTree() {
   
        if (bodyList != null && !bodyList.isEmpty()) {
   
            // 声明 map,用来过滤已操作过的数据
            Map<Long, Long> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree, map));
            return rootList;
        }
        return null;
    }

    // 递归实现获取子集
    public void getChild(ResourceTreeVO beanTree, Map<Long, Long> map) {
   
        List<ResourceTreeVO> childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getResourceId()))
                .filter(c -> c.getParentId().equals(beanTree.getResourceId()))
                .forEach(c -> {
   
                    map.put(c.getResourceId(), c.getParentId());
                    getChild(c, map);
                    childList.add(c);
                });
        beanTree.setChildren(childList);
    }

}

三、基于Model数据,构建资源树

    public List<ResourceTreeVO> ListTree() {
   
        List<ResourceTreeVO> treeVOList = this.list(null).stream().map(ResourceTreeVO::new).collect(Collectors.toList());
        // 先找到根节点
        List<ResourceTreeVO> rootList = treeVOList.stream()
                .filter(e -> ResourceLevelEnum.FIRST_LEVEL.getLevel().equals(e.getLevel()))
                .collect(Collectors.toList());
        // 子节点元数据
        List<ResourceTreeVO> bodyList = treeVOList.stream()
                .filter(e -> !ResourceLevelEnum.FIRST_LEVEL.getLevel().equals(e.getLevel()))
                .collect(Collectors.toList());

        ResourceTreeUtil treeUtil = new ResourceTreeUtil(rootList, bodyList);
        return treeUtil.getTree();
    }