Java由HashMap生成树形菜单/部门

时间:2021-05-13 12:38:28

1.获取部门列表

2.根据部门的Id映射部门实体类

先看下部门实体类

public class TbEnterpriseDepartment {
private int id;
private String name;
private int number;
private int parentId;
private List<TbEnterpriseDepartment> childDeparents;
public TbEnterpriseDepartment() {
}

public TbEnterpriseDepartment(int id, String name, int parentId, boolean isRoot) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.isRoot = isRoot;
}

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 getNumber() {
return number;
}

public void setNumber(int number) {
this.number = number;
}

public int getParentId() {
return parentId;
}

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

@Override
public String toString() {
return JSON.toJSONString(this);
}

public List<TbEnterpriseDepartment> getChildDeparents() {
return childDeparents;
}

public void setChildDeparents(List<TbEnterpriseDepartment> childDeparents) {
this.childDeparents = childDeparents;
}
//添加子部门
public void addChildDepartment(TbEnterpriseDepartment department) {
if(this.childDeparents == null)
this.childDeparents = new LinkedList<>();
this.childDeparents.add(department);
}
}

3.然后遍历之前的部门列表,把部门加入到父部门的child列表中。

4.打印输出JSON

5.代码

@Test
public void test() {
//初始化列表
List<TbEnterpriseDepartment> departments = new ArrayList<>();
TbEnterpriseDepartment rootDepartment = new TbEnterpriseDepartment(1,"root-1",-1,true);
departments.add(new TbEnterpriseDepartment(2,"root-1-1",1,false));
departments.add(new TbEnterpriseDepartment(3,"root-1-1-1",2,false));
departments.add(new TbEnterpriseDepartment(4,"root-1-1-2",2,false));
departments.add(new TbEnterpriseDepartment(5,"root-1-2",1,false));
departments.add(new TbEnterpriseDepartment(6,"root-1-2-1",5,false));
departments.add(rootDepartment);

HashMap<Integer,TbEnterpriseDepartment>departmentMap = new HashMap<>();

//初始化HashMap
for (TbEnterpriseDepartment department : departments) {
departmentMap.put(department.getId(),department);
}
//遍历添加
for (TbEnterpriseDepartment department : departments) {
//如果确定parentId一定存在去除此条件 if(departmentMap.containsKey(department.getParentId())){
departmentMap.get(department.getParentId()).addChildDepartment(department);
}
}
System.out.println(rootDepartment);
//结果
//{"childDepartments":[{"childDepartments":[{"id":3,"name":"root-1-1-1","parentId":2},{"id":4,"name":"root-1-1-2","parentId":2}],"id":2,"name":"root-1-1","parentId":1},{"childDepartments":[{"id":6,"name":"root-1-2-1","parentId":5}],"id":5,"name":"root-1-2","parentId":1}],"id":1,"name":"root-1","parentId":-1}
}

在HashMap的理想情况下复杂度为O(n)