java生成树(generateTree)

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

//生成权限树
public List<Tree> generateTree(List<Tree> treeList) {
    if (CollectionUtils.isEmpty(treeList)) {
        return null;
    }
    Map<Long, Tree> nodeMap = new HashMap<>();
    for (Tree tree : treeList) {
        nodeMap.put(tree.getId(), tree);
    }
    List<Tree> 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;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值