java树级对象递归查找子集问题

比方有一个类是dept,里面属性是id(部门id)唯一不重复,name(部门名称),parId(部门父id),有一个变量Map<Integer,List<Integer>> map,key是部门id,List<Integer>是这个部门的子部门,现在数据如下
id name parId
1 部门1 0
2 部门2 1
3 部门3 1
4 部门4 1
5 部门5 2
6 部门6 3
7 部门7 2
8 部门8 2
9 部门9 1
10 部门10 5
上面有9条数据,就有9个dept变量
所以map应该是1={2,3,4,5,6,7,8,9},2={5,7,8,10},3={6}
虽然知道要用递归去不断找出所有部门id的子集id,可是不知道应该要怎么写,想请懂的人给个思路或者方向,不胜感激

package com.demo.dept;

/**
 * @author dongbin.yu
 * @from 2016-05-06
 * @since V1.0
 */
public class Dept {

    private int id;

    private String name;

    private int parentId;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getParentId() {
        return parentId;
    }

    public void setParentId(int parentId) {
        this.parentId = parentId;
    }

    public Dept(int id, String name, int parentId) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
    }
}

package com.demo.dept;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dongbin.yu
 * @from 2016-05-06
 * @since V1.0
 */
public class DeptTest {

    private static List<Dept> depts = new ArrayList<>();

    static{
        depts.add(new Dept(1,"部门1",0));
        depts.add(new Dept(2,"部门2",1));
        depts.add(new Dept(3,"部门3",1));
        depts.add(new Dept(4,"部门4",1));
        depts.add(new Dept(5,"部门5",2));
        depts.add(new Dept(6,"部门6",3));
        depts.add(new Dept(7,"部门7",2));
        depts.add(new Dept(8,"部门8",2));
        depts.add(new Dept(9,"部门9",1));
        depts.add(new Dept(10,"部门10",5));
    }

    public static void main(String[] args) {
        Map<Integer, List<Integer>> deptMap = new HashMap<>();

        for (Dept dept : depts) {
            deptMap.put(dept.getId(),getChildDept(dept.getId()));
        }

        System.out.println(deptMap);

    }

    private static List<Integer> getChildDept(int id){
        List<Integer> ids = new ArrayList<>();

        for (Dept dept : depts) {
            if(dept.getParentId() == id){
                //添加第一次父id符合的
                ids.add(dept.getId());
                //添加嵌套父id符合的
                ids.addAll(getChildDept(dept.getId()));
            }
        }
                Collections.sort(ids);
        return ids;
    }

}

温馨提示:答案为网友推荐,仅供参考
相似回答