1. 程式人生 > >父子結構數據(id,pid)遞歸查詢所有子id合集和父id合集

父子結構數據(id,pid)遞歸查詢所有子id合集和父id合集

dal tde main 測試 實體類 static != private 部門

查詢子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) {
            int count = 0;
            for (Integer i : set) {

                if (i.equals(new Integer(depart.getPid()))) {
                    set1.add(depart.getId());
                    intset.add(depart.getId());
                    count++;
                }
                if (count != 0) {
                    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);
    }

父子結構數據(id,pid)遞歸查詢所有子id合集和父id合集