天天看點

根據層級關系,建構樹形結構資料

根據層級關系,建構樹形結構資料

  • ​​一、基本模型​​
  • ​​二、遞歸工具類​​
  • ​​三、基于Model資料,建構資源樹​​

一、基本模型

@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() {
    }
}      

二、遞歸工具類

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();
    }