现有一个需求,另存现有的部门的多级菜单 多级树形结构,形成新的部门的多级菜单 多级树形结构,只是部门名称不一样,内容是一样的,本人是新学java没多久,请各位java大拿提供一下实现思路,最好有代码
部门实体类:
package mianshi.算法.递归算法.组织树;
import java.util.ArrayList;
import java.util.List;
public class Dept {
private Integer id;
private Integer parentId;
private List<Dept> children = new ArrayList<Dept>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public List<Dept> getChildren() {
return children;
}
public void setChildren(List<Dept> children) {
this.children = children;
}
@Override
public String toString() {
return "Dept [id=" + id + ", parentId=" + parentId + ", children="
+ children + "]";
}
}
遍历树:
package mianshi.算法.递归算法.组织树;
import java.util.ArrayList;
import java.util.List;
public class DeptTest {
private static Dept root;
private static List<Dept> dataBaseList;
public static void main(String[] args) {
dataBaseList = new ArrayList<Dept>();
root = new Dept();
root.setId(1);
root.setParentId(0);
dataBaseList.add(root);
Dept d1_1 = new Dept();
d1_1.setId(2);
d1_1.setParentId(1);
Dept d1_2 = new Dept();
d1_2.setId(3);
d1_2.setParentId(1);
dataBaseList.add(d1_1);
dataBaseList.add(d1_2);
Dept d1_1_1 = new Dept();
d1_1_1.setId(4);
d1_1_1.setParentId(2);
Dept d1_1_2 = new Dept();
d1_1_2.setId(5);
d1_1_2.setParentId(2);
dataBaseList.add(d1_1_1);
dataBaseList.add(d1_1_2);
d1_1.getChildren().add(d1_1_1);
d1_1.getChildren().add(d1_1_2);
root.getChildren().add(d1_1);
root.getChildren().add(d1_2);
System.out.println(root);
Dept newRoot = new Dept();
newRoot.setId(1);
newRoot.setParentId(0);
getChildren(1,newRoot);
System.out.println(newRoot);
}
/*
* 树形菜单结构:
* --1
* --2
* --4
* --5
* --3
*
* Dept [id=1, parentId=0,
* children=[Dept [id=2, parentId=1,
* children=[Dept [id=4, parentId=2, children=[]],
* Dept [id=5, parentId=2, children=[]]]],
* Dept [id=3, parentId=1, children=[]]]]
*/
private static List<Dept> getChildren(int id,Dept dept) {
// 模拟数据库查询parentId为id的下面的子节点
List<Dept> deptList = getData(id);
if(deptList != null){
// 节点下面的子节点
dept.setChildren(deptList);
for(Dept deptItem : deptList){
// 递归调用
getChildren(deptItem.getId(), deptItem);
}
}
return deptList;
}
private static List<Dept> getData(int id) {
List<Dept> list = new ArrayList<Dept>();
for(Dept dept : dataBaseList){
if(dept.getParentId().equals(id)){
list.add(dept);
}
}
return list;
}
}