@Data
@ToString
public class Dept {
/**
* 部门ID
*/
private int id;
/**
* 父级ID
* 视情况返回前端(这里不返回)
*/
@JsonIgnore
private int parentId;
/**
* 部门名称
*/
private String name;
/**
* 部门子集
*/
private List<Dept> child;
}
public class DeptHelper {
public static void main(String[] args) {
List<Dept> mockData = initList();
List<Dept> deptTree = processTree(mockData, 0);
System.out.println("deptTree:" + deptTree);
}
private static List<Dept> processTree(List<Dept> mockData, int id) {
//按指定节点过滤数据
List<Dept> master = mockData.stream().filter(dept -> dept.getParentId() == id).collect(Collectors.toList());
//将过滤出的节点从数据中移除
mockData.removeAll(master);
//构建分支节点
List<Dept> branch = new ArrayList<>();
master.forEach(dept -> {
//递归获取分支节点
dept.setChild(processTree(mockData, dept.getId()));
//将分支节点加入父节点中
branch.add(dept);
});
return branch;
}
/**
* 初始化数据
* @return 初始化数据
*/
private static List<Dept> initList() {
List<Dept> all = new ArrayList<>();
Dept master = new Dept();
master.setId(1);
master.setParentId(0);
master.setName("集团总部");
all.add(master);
Dept changSha = new Dept();
changSha.setId(2);
changSha.setParentId(1);
changSha.setName("长沙分公司");
all.add(changSha);
Dept beiJing = new Dept();
beiJing.setId(3);
beiJing.setParentId(1);
beiJing.setName("北京分公司");
all.add(beiJing);
Dept chengDu = new Dept();
chengDu.setId(4);
chengDu.setParentId(1);
chengDu.setName("成都分公司");
all.add(chengDu);
Dept cs1 = new Dept();
cs1.setId(5);
cs1.setParentId(2);
cs1.setName("市场部");
all.add(cs1);
Dept cs2 = new Dept();
cs2.setId(6);
cs2.setParentId(2);
cs2.setName("投资部");
all.add(cs2);
Dept bj1 = new Dept();
bj1.setId(7);
bj1.setParentId(3);
bj1.setName("研发部");
all.add(bj1);
Dept cd1 = new Dept();
cd1.setId(8);
cd1.setParentId(4);
cd1.setName("媒体部");
all.add(cd1);
Dept mt1 = new Dept();
mt1.setId(9);
mt1.setParentId(8);
mt1.setName("设计部");
all.add(mt1);
return all;
}
}