父子结构数据(id,pid)递归查询所有子id合集和父id合集
查询子id合集
创建实体类
@Data public class Department {
private int id; private int pid; private String name; public Department(int id, int pid, String name) { this.id = id; this.pid = pid; this.name = name; }
方法
//递归查询子部门---lists所有部门合集,set为id合集,
private static Set<Integer> intset = new HashSet<>();
private static void getChiildrenDepartment(List<Department> lists, Set<Integer> set) {
Set<Integer> set1 = new HashSet<>();
for (Department depart : lists) {
for (Integer i : set) {
if (i.equals(new Integer(depart.getPid()))) {
set1.add(depart.getId());
intset.add(depart.getId());
getChiildrenDepartment(lists, set1);
}
}
}
}
//递归查询父部门---lists所有部门合集,set为id合集,topId为顶层id
private static void getParentDepartmnet(List<Department> lists, Set<Integer> set, int topId){
Set<Integer> set1 = new HashSet<>();
for (Department depart : lists) {
for (Integer i : set) {
if (i.equals(new Integer(depart.getId()))) {
set1.add(depart.getPid());
intset.add(depart.getPid());
}
if( depart.getPid() == topId){
continue;
}else {
getParentDepartmnet(lists, set1, topId);
}
}
}
}
测试
public static void main(String[] args) { Department d1 = new Department(1, 0, "总部"); Department d2 = new Department(2, 1, "分部2"); Department d3 = new Department(3, 1, "分部3"); Department d4 = new Department(4, 1, "分部4"); Department d5 = new Department(5, 2, "分部2子部1"); Department d6 = new Department(6, 2, "分部2子部2"); Department d7 = new Department(7, 3, "分部3子部1"); List<Department> list = new ArrayList<>(); list.add(d1); list.add(d2); list.add(d3); list.add(d4); list.add(d5); list.add(d6); list.add(d7); Set<Integer> set = new HashSet<>(); set.add(7); getChiildrenDepartment(list, set); System.out.println(intset); intset.addAll(set); System.out.println(intset); intset.clear(); getParentDepartmnet(list, set,0); System.out.println(intset); intset.addAll(set); System.out.println(intset); }