java部门树的递归


部门对象

package com.qcf.po;
import java.util.HashSet;
import java.util.Set;
public class Depart {
    private long id;
    private String name;
    private String destion;
    //用户
    Set<User> users=new HashSet<User>();
    //子类部门
    Set<Depart> departs=new HashSet<Depart>();
    //父类部门
    private Depart depart;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<User> getUsers() {
        return users;
    }
    public void setUsers(Set<User> users) {
        this.users = users;
    }
    public Set<Depart> getDeparts() {
        return departs;
    }
    public void setDeparts(Set<Depart> departs) {
        this.departs = departs;
    }
    public Depart getDepart() {
        return depart;
    }
    public void setDepart(Depart depart) {
        this.depart = depart;
    }
    public String getDestion() {
        return destion;
    }
    public void setDestion(String destion) {
        this.destion = destion;
    }
}

递归实现

package com.ytx.demo.tree;

import java.util.ArrayList;
import java.util.List;

public class DempartmentThree {
public static void main(String[] args) {
    List departmentList = new ArrayList<>();
    departmentList.add(new Department(1, "研发部门", 0));
    departmentList.add(new Department(2, "研发团队1", 1));
    departmentList.add(new Department(3, "研发团队2", 1));
    departmentList.add(new Department(4, "财务部门", 0));
    departmentList.add(new Department(5, "财务A部门", 4));
    departmentList.add(new Department(6, "财务B部门", 4));
    departmentList.add(new Department(7, "财务A部门团队1", 5));
    departmentList.add(new Department(8, "财务A部门团队2", 5));
    departmentList.add(new Department(9, "财务B部门团队1", 6));
    departmentList.add(new Department(10, "财务B部门团队2", 6));

    List listTree = getThree(departmentList,0);
    System.out.println(listTree);
}

private static List getThree(List list,int parentId){
    //获取所有子节点
    List childTreeList = getChildTree(list,parentId);
    for (Department dept:childTreeList) {
        dept.setChildren(getThree(list,dept.getId()));
    }
    return childTreeList;
}

private static List getChildTree(List list,int id){
    List childTree = new ArrayList<>();
    for (Department dept:list) {
        if(dept.getParentId() == id){
            childTree.add(dept);
        }
    }
    return childTree;
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM