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;
}
}
温馨提示:答案为网友推荐,仅供参考