java生成树(generateTree)

 
  
参考:https://blog.csdn.net/mynamepg/article/details/79802885

//生成权限树
public List generateTree(List treeList) {
    if (CollectionUtils.isEmpty(treeList)) {
        return null;
    }
    Map nodeMap = new HashMap<>();
    for (Tree tree : treeList) {
        nodeMap.put(tree.getId(), tree);
    }
    List rootList = new ArrayList<>();
    //建立父子关系
    for (Tree node : nodeMap.values()) {
        Long parentId = node.getParentId();
        if (parentId == null) {
            rootList.add(node);
            continue;
        }
        if (nodeMap.containsKey(parentId)) {
            Tree parentNode = nodeMap.get(parentId);
            parentNode.addChildNode(node);
        }
    }
    // sort
    for (Tree t : nodeMap.values()) {
        List children = t.getChildren();
        if (children != null && children.size() > 0) {
            t.sortChildren(children);
        }
    }
    Collections.sort(rootList);
    return rootList;
}

      /**
        * 具体树节点        */
 public class Tree extends TreeNode implements Comparable<CostCenterNode>{
    private String code;
    private int position;
    private int employeeCount;

    @Override
    public boolean isRoot(String parentId) {
        if (StringUtil.isEmpty(parentId)) {
            return true;
        }
        return false;
    }

    @Override
    public void sortChildren(List children) {
        Collections.sort(children);
    }

    public CostCenterNode(CostCenterDO centerDO) {
        this.setId(centerDO.getCostId());
        this.setParentId(centerDO.getParentId());
        this.setName(centerDO.getName());
        this.setCode(centerDO.getCode());
        this.setPosition(centerDO.getPosition());
        this.setChildren(new ArrayList());
    }

    // getter setter

    @Override
    public int compareTo(CostCenterNode o) {
        // 按照position升序排列
        if (this.position > o.getPosition()) {
            return 1;
        } else {
            return -1;
        }
    }
}


你可能感兴趣的:(java树生成)