package com.iplatform.base.util.menu;
|
|
import com.iplatform.model.vo.MenuVo;
|
import com.walker.infrastructure.utils.StringUtils;
|
|
import java.util.ArrayList;
|
import java.util.Comparator;
|
import java.util.List;
|
import java.util.stream.Collectors;
|
|
/**
|
* 新界面菜单树构建对象。
|
* @author 时克英
|
* @date 2023-05-12
|
*/
|
public class MenuTree {
|
|
private List<MenuVo> menuList = new ArrayList<>();
|
|
public MenuTree(List<MenuVo> menuList) {
|
this.menuList = menuList;
|
}
|
|
//建立树形结构
|
public List<MenuVo> buildTree() {
|
List<MenuVo> treeMenus = new ArrayList<>();
|
for (MenuVo menuNode : getRootNode()) {
|
menuNode = buildChildTree(menuNode);
|
treeMenus.add(menuNode);
|
}
|
return sortList(treeMenus);
|
}
|
|
// 排序
|
private List<MenuVo> sortList(List<MenuVo> treeMenus) {
|
treeMenus = treeMenus.stream().sorted(Comparator.comparing(MenuVo::getSort).reversed()).collect(Collectors.toList());
|
treeMenus.forEach(e -> {
|
if (!StringUtils.isEmptyList(e.getChildList())) {
|
e.setChildList(sortList(e.getChildList()));
|
}
|
});
|
return treeMenus;
|
}
|
|
//递归,建立子树形结构
|
private MenuVo buildChildTree(MenuVo pNode) {
|
List<MenuVo> childMenus = new ArrayList<>();
|
for (MenuVo menuNode : menuList) {
|
if (menuNode.getPid().equals(pNode.getId())) {
|
childMenus.add(buildChildTree(menuNode));
|
}
|
}
|
pNode.setChildList(childMenus);
|
return pNode;
|
}
|
|
//获取根节点
|
private List<MenuVo> getRootNode() {
|
List<MenuVo> rootMenuLists = new ArrayList<MenuVo>();
|
for (MenuVo menuNode : menuList) {
|
if (menuNode.getPid().longValue() == 0) {
|
rootMenuLists.add(menuNode);
|
}
|
}
|
return rootMenuLists;
|
}
|
}
|