背景介绍
我有一个部门的表结构,如果我获取到下列数据,如何通过后端来构造该公司的树形结构
代码
- POJO类
import java.util.List;
public class Company {
private int id;//公司id
private String name;//公司名称
private int pid;//上级公司
private List<Company> subCompanyList;//下游公司
public Company() {
}
public Company(int id, String name, int pid) {
this.id = id;
this.name = name;
this.pid = pid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public List<Company> getSubCompanyList() {
return subCompanyList;
}
public void setSubCompanyList(List<Company> subCompanyList) {
this.subCompanyList = subCompanyList;
}
@Override
public String toString() {
return "Company{" +
"id=" + id +
", name='" + name + '\'' +
", pid=" + pid +
", subCompanyList=" + subCompanyList +
'}';
}
}
- 递归方法
public static Company addSubCompany(Company company,List<Company> data){
//构造一个子公司列表
List<Company> subCompany = new ArrayList<>();
for(Company item: data){//遍历数据
//如果遍历到的部门是当前部门的子部门
if(item.getPid() == company.getId()){
//把遍历到的公司添加到子公司列表,并且递归地调用本方法
subCompany.add(addSubCompany(item,data));
}
}
company.setSubCompanyList(subCompany);
return company;
}
- 具体测试类
这里为了方便,就不搞DAO层了,自己模拟一些数据代替
public static void main(String[] args) {
List<Company> data = new ArrayList<>();
Company c1 = new Company(1,"总公司",-1);
Company c2 = new Company(10,"财务部",1);
Company c3 = new Company(11,"市场部",1);
Company c4 = new Company(12,"研发部",1);
Company c5 = new Company(100,"财务小组1",10);
Company c6 = new Company(101,"财务小组2",10);
Company c7 = new Company(110,"市场小组1",11);
Company c8 = new Company(111,"市场小组2",11);
Company c9 = new Company(120,"研发小组1",12);
Company c10 = new Company(121,"研发小组2",12);
data.add(c1);data.add(c2);data.add(c3);data.add(c4);data.add(c5);
data.add(c6);data.add(c7);data.add(c8);data.add(c9);data.add(c10);
addSubCompany(c1,data);
System.out.println(c1);
}
运行结果
Company{id=1, name='总公司', pid=-1, subCompanyList=[Company{id=10, name='财务部', pid=1, subCompanyList=[Company{id=100, name='财务小组1', pid=10, subCompanyList=[]}, Company{id=101, name='财务小组2', pid=10, subCompanyList=[]}]}, Company{id=11, name='市场部', pid=1, subCompanyList=[Company{id=110, name='市场小组1', pid=11, subCompanyList=[]}, Company{id=111, name='市场小组2', pid=11, subCompanyList=[]}]}, Company{id=12, name='研发部', pid=1, subCompanyList=[Company{id=120, name='研发小组1', pid=12, subCompanyList=[]}, Company{id=121, name='研发小组2', pid=12, subCompanyList=[]}]}]}
Process finished with exit code 0