递归封装层级菜单(java)
解决方法:
1.menuList就是递归后封装的层级菜单
//rootMenu所有菜单的集合
List<Map<Object, Object>> rootMenu = baseService.excuteQueryList(sql, null);
List<Map<Object, Object>> menuList = new ArrayList<Map<Object, Object>>();
// 先找到所有的一级菜单
for (int i = 0; i < rootMenu.size(); i++) {
// 一级菜单没有parentId
if ("0".equals(rootMenu.get(i).get("parentId").toString())) {
menuList.add(rootMenu.get(i));
}
}
// 为一级菜单设置子菜单,getChild是递归调用的
for (Map<Object, Object> menu : menuList) {
List<Map<Object, Object>> childs = getChild(menu.get("id").toString(), rootMenu);
if(childs!=null&&childs.size()>0){
menu.put("childs",childs);
}
}
2.递归查找子菜单
private List<Map<Object, Object>> getChild(String id, List<Map<Object, Object>> rootMenu) {
// 子菜单
List<Map<Object, Object>> childList = new ArrayList<Map<Object, Object>>();
for (Map<Object, Object> menu : rootMenu) {
// 遍历所有节点,将父菜单id与传过来的id比较
if (StringUtils.isNotBlank(menu.get("parentId").toString())) {
if (menu.get("parentId").toString().equals(id)) {
childList.add(menu);
}
}
}
// 把子菜单的子菜单再循环一遍
for (Map<Object, Object> menu : childList) {// 没有url子菜单还有子菜单
if (StringUtils.isNotBlank(menu.get("parentId").toString())) {
// 递归
List<Map<Object, Object>> childs = getChild(menu.get("id").toString(), rootMenu);
if(childs!=null&&childs.size()>0){
menu.put("childs",childs);
}
}
} // 递归退出条件
if (childList.size() == 0) {
return null;
}
return childList;
}