美文网首页
1.java基础- java List 转 tree (树形结构

1.java基础- java List 转 tree (树形结构

作者: 那钱有着落吗 | 来源:发表于2021-08-20 09:58 被阅读0次

    原理就是回调函数,迭代

    public class TreeNode {
    
        private String id;
        private String pid;
        private String name;
        private List<TreeNode> children = new ArrayList<>();
    
        public TreeNode() {
            
        }
    
        public TreeNode(String id, String pid, String name) {
            this.id = id;
            this.pid = pid;
            this.name = name;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getPid() {
            return pid;
        }
    
        public void setPid(String pid) {
            this.pid = pid;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public List<TreeNode> getChildren() {
            return children;
        }
    
        public void setChildren(List<TreeNode> children) {
            this.children = children;
        }
    
    }
    
    private List<TreeNode> buildTree(List<TreeNode> nodeList){
            List<TreeNode> result = new ArrayList<>();
            for (TreeNode zone:nodeList) {
                if (zone.getPid().equals("0")) {
                    result.add(zone);
                    setChildren(nodeList, zone);
                }
            }
            return result;
        }
    
        public static void setChildren(List<TreeNode> list, TreeNode parent) {
            for (TreeNode zone: list) {
                if(parent.getId().equals(zone.getPid())){
                    parent.getChildren().add(zone);
                }
            }
            if (parent.getChildren().isEmpty()) {
                return;
            }
            for (TreeNode zone: parent.getChildren()) {
                setChildren(list, zone);
            }
        }
    

    相关文章

      网友评论

          本文标题:1.java基础- java List 转 tree (树形结构

          本文链接:https://www.haomeiwen.com/subject/prkabltx.html