验证中...
Languages: Java
Categories: Web开发技术
Latest update 2019-08-26 11:05
层级菜单生成树
Raw Copy
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class MenuTree {
public static void main(String[] args) {
List<Menu> list = new ArrayList<>();
//TODO 这里从数据库获取全量菜单后放到list中
Menu m1 = new Menu();
m1.setId("Z01");
m1.setPid("0");
m1.setTitle("顶级节点");
list.add(m1);
Menu m2 = new Menu();
m2.setId("01");
m2.setPid("Z01");
m2.setTitle("二级节点");
list.add(m2);
Menu m21 = new Menu();
m21.setId("011");
m21.setPid("01");
m21.setTitle("三级节点");
list.add(m21);
Menu m3 = new Menu();
m3.setId("02");
m3.setPid("Z01");
m3.setTitle("二级节点");
list.add(m3);
//树形结构数据生成
List<Menu> result = parseMenuTree(list);
System.out.println(JSON.toJSONString(result));
}
/**
* @param list 数据库里面获取到的全量菜单列表
* @描述: 组装菜单
*/
public static List<Menu> parseMenuTree(List<Menu> list) {
List<Menu> res = new ArrayList<>();
//1:获取第一级节点
list.parallelStream().forEach(menu -> {
if ("0".equals(menu.getPid())) {
res.add(menu);
}
});
//2:递归获取子节点
res.parallelStream().forEach(p -> {
p = recursiveTree(p, list);
});
return res;
}
//递归对比所有数据
public static Menu recursiveTree(Menu pmenu, List<Menu> list) {
list.parallelStream().forEach(menu -> {
if (pmenu.getId().equals(menu.getPid())) {
menu = recursiveTree(menu, list);
pmenu.getChildren().add(menu);
}
});
return pmenu;
}
//菜单
public static class Menu {
private String id;
private String title;//菜单标题
private String pid;//父菜单ID 一级菜单pid为null
private List<Menu> children = new LinkedList<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public List<Menu> getChildren() {
return children;
}
public void setChildren(List<Menu> children) {
this.children = children;
}
}
}

Comment list( 1 )

1370710_zhengshunzi
zhengshunzhi 2019-08-26 11:05

运行结果:[{"children":[{"children":[{"children":[],"id":"011","pid":"01","title":"三级节点"}],"id":"01","pid":"Z01","title":"二级节点"},{"children":[],"id":"02","pid":"Z01","title":"二级节点"}],"id":"Z01","pid":"0","title":"顶级节点"}]

You need to Sign in for post a comment

Help Search