Java中list转树

原创
2019/10/13 09:58
阅读数 298
public class TreeNode {
 
    private String id;
 
    private String parentId;
 
    private String name;
 
    private List<TreeNode> children;
 
    public TreeNode(String id, String name, String parentId) {
        this.id = id;
        this.parentId = parentId;
        this.name = name;
    }
    public TreeNode(String id, String name, TreeNode parent) {
        this.id = id;
        this.parentId = parent.getId();
        this.name = name;
    }
 
 
    public String getParentId() {
        return parentId;
    }
 
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public List<TreeNode> getChildren() {
        return children;
    }
 
    public void setChildren(List<TreeNode> children) {
        this.children = children;
    }
 
    @Override
    public String toString() {
        return "TreeNode{" +
                "id='" + id + '\'' +
                ", parentId='" + parentId + '\'' +
                ", name='" + name + '\'' +
                ", children=" + children +
                '}';
    }
 
}


public class TreeBuilder {
 
    /**
     * 两层循环实现建树
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public static List<TreeNode> bulid(List<TreeNode> treeNodes) {
 
        List<TreeNode> trees = new ArrayList<TreeNode>();
 
        for (TreeNode treeNode : treeNodes) {
 
            if ("0".equals(treeNode.getParentId())) {
                trees.add(treeNode);
            }
 
            for (TreeNode it : treeNodes) {
                if (it.getParentId() == treeNode.getId()) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<TreeNode>());
                    }
                    treeNode.getChildren().add(it);
                }
            }
        }
        return trees;
    }

}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部