要求:
工作需要,需要通过已得到的部门,获取部门的父部门,父部门的父部门,甚至更往上
(每个部门存在自身的ID号以及父部门的ID号,位于最顶端的部门的父部门ID号为0)
预先准备:
(1)List<Department> departments:已经获取到的部门集合
(2)Set<String> partentDeptId:存放已经得到部门的父ID
(3)Set<Long> deptId:存放已经得到部门的ID(由于的deptId和partentDeptId字段类型不同,所以一个是String类型,一个是Long类型)
(4)操作:遍历List<Department>集合 departments,将department.partentDepId添加进Set<String> 集合partentDeptId中;
同理,将department.id添加进Set<Long> 集合deptId。
代码实现:
(1)、将预先准备好的三个集合作为参数传递进方法:
List<Department> ergodicDept(List<Department> departments,Set<String> partentDeptId,Set<Long> deptId)中
,并接收返回值List<Department>
(2)、编写(1)中提到的方法代码:
/*
ergodicDept遍历寻找父类
*/
public List<Department> ergodicDept(List<Department> departments,Set<String> partentDeptId,
Set<Long> deptId){
Set<String> copyPartentDeptId=new HashSet<String>();
for(String parId:partentDeptId){
copyPartentDeptId.add(parId);
}
for(String parId:copyPartentDeptId){
if(!"0".equals(parId)){
//获得父部门
Department department = departmentAccessService.findById(Long.valueOf(parId));
//删掉已使用的父id
partentDeptId.remove(parId);
//判断得到的父亲部门是否存在//不存在
if(deptId.add(department.getId())){
//不存在则添加
departments.add(department);
partentDeptId.add(department.getParentId());
}
}
}//判断新加入的父节点是否只有0,并且只有一个
if(partentDeptId.size()==1&&!partentDeptId.add("0")){
return departments;
}else {
return ergodicDept(departments,partentDeptId,deptId);
}
}
代码尚存多处不足,甚至多处问题,尚需改进之处很多