欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

通过lambda实现菜单树形结构

程序员文章站 2022-07-10 17:37:04
...
public List<CategoryEntity> listWithTree() {
    //1、查出所有分类
    List<CategoryEntity> list = baseMapper.selectList(null);
    //2、组装树形结构
    List<CategoryEntity> level1Menus = list.stream()
            .filter(t -> t.getParentCid() == 0)
            .map((menu) -> {
                menu.setChildren(this.getChildren(menu,list));
                return menu;
            })
            .sorted((menu1,menu2) -> {return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()) ;})
            .collect(Collectors.toList());

    return level1Menus;
}
/**
 * 递归查找当前菜单的子菜单
 * @param root
 * @param all
 * @return
 */
private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
    List<CategoryEntity> childrenList = all.stream()
            .filter(t -> t.getParentCid() == root.getCatId())
            .map(g -> {
                //找子菜单
                g.setChildren(getChildren(g,all));
                return g;
            })
            //菜单排序
            .sorted((menu1,menu2) -> {return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()) ;})
            .collect(Collectors.toList());

    return childrenList;
}

注意:主要要有catId也就是主键ID,和parentCId也就是父ID,还要有每条记录的sort顺序。
当前CategoryEntity实体类里有List children;用来存储子菜单的。

如果要用的话,jdk1.8及以上即可。