【无标题】java实现多级菜单(递归)

生成树的方法:```
//1.查出所有分类entities
List entities = baseMapper.selectList(null);
//2、组装成父子的树形结构(leveMenus 一级分类目录)
List leveMenus = new ArrayList<>();
//2.1)、找到所有的一级分类
//getParentCid()该字段0表示一级目录,1表示二级 以此类推
for (CategoryEntity entitie: entities) {
//Long parentCid = entitie.getParentCid();
if (entitie.getParentCid()== 0 ){
leveMenus.add(entitie);
}
}
Collections.sort(leveMenus,order());//根据order排序;Collections的sourt排序方法
//对一级目录进行遍历获取子目录,其中getChildrens方法在后面
for (CategoryEntity nav:leveMenus
) {
List childrenss = getChildrens(nav,entities);//获取子菜单
nav.setChildren(childrenss);
}
return leveMenus;
}

**获取子菜单:**

//递归查找所有菜单的子菜单 root 当前分类目录 ,all 所有分类
private List getChildrens(CategoryEntity root,List all){
List childrenList = new ArrayList<>();
//遍历所有菜单,如果当前的菜单的分类id(catid)等于便利的父分类id;则说明该菜单是便利的父节点
for (CategoryEntity entitie: all) {
if(entitie.getParentCid()==root.getCatId()){
childrenList.add(entitie);
}
}
//递归
for (CategoryEntity children:childrenList){
children.setChildren(getChildrens(children, all));
}
//排序
Collections.sort(childrenList,order());

    return childrenList;
    }

你可能感兴趣的:(java,开发语言,后端)