部門對象
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;
}
}