java实现多级菜单
/**
* 查询所有菜单
*/
public BaseWebResponse<Object> getAllMenus() {
List<SystemMenuInfo> systemMenuInfoList = menuInfoMapper.getAllMenus();
List<SystemMenuInfo> menuTree = buildMenuTree(systemMenuInfoList);
return setResultSuccess("信息查询成功", menuTree);
}
/**
* 构建菜单树
*/
private List<SystemMenuInfo> buildMenuTree(List<SystemMenuInfo> allMenus) {
//用于存放根菜单
List<SystemMenuInfo> rootMenus = new ArrayList<>();
Map<Integer, List<SystemMenuInfo>> menuMap = new HashMap<>();
// 将菜单按照父菜单ID分组,放在menuMap中
for (SystemMenuInfo menu : allMenus) {
int parentId = menu.getPid() != null ? menu.getPid() : 0;
if (!menuMap.containsKey(parentId)) {
menuMap.put(parentId, new ArrayList<>());
}
menuMap.get(parentId).add(menu);
}
// 从根菜单开始,构建菜单树
rootMenus.addAll(menuMap.getOrDefault(0, new ArrayList<>()));
for (SystemMenuInfo rootMenu : rootMenus) {
buildSubMenuTree(rootMenu, menuMap);
}
return rootMenus;
}
/**
* 根据父菜单节点逐级构建子树,按顺序排列
*/
private void buildSubMenuTree(SystemMenuInfo parentMenu, Map<Integer, List<SystemMenuInfo>> menuMap) {
//获取根菜单的子节点列表
List<SystemMenuInfo> children = menuMap.getOrDefault(parentMenu.getMenuId(), new ArrayList<>());
Collections.sort(children);
parentMenu.setChildren(children);
for (SystemMenuInfo childMenu : children) {
buildSubMenuTree(childMenu, menuMap);
}
}