N级树形菜单封装

N级树形菜单封装

每次遇到这样的需求,虽然能写出来,但是每次还是要费一点脑细胞,写了一个复用性强的,方便以后

public List<CategoryEntity> listToTree() {
    //1、查出所有分类
    List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

    //1.1 filter 找到所有一级分类
    //1.2 map 找到其下的所有子节点
    //1.3 sorted 排序
    //1.4 collect 形成新的集合
    List<CategoryEntity> collect = categoryEntities.stream()
            .filter(entity -> entity.getParentCid() == 0)
            .map(entity -> {
                entity.setChildrens(getChildre(entity,categoryEntities));
                return entity;
            })
            .sorted((var1, var2) -> {
                return (var1.getSort() == null ? 0 : var1.getSort()) - (var2.getSort() == null ? 0 : var2.getSort());
            })
            .collect(Collectors.toList());
    return collect;
}
//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildre(CategoryEntity root ,List<CategoryEntity> list){

    List<CategoryEntity> collect = list.stream()
            //1 filter 找到子节点
            .filter(children -> {
                return children.getParentCid() == root.getCatId();
            })
            //2 递归封装其下所有自己点
            .map(children -> {
                children.setChildrens(getChildre(children, list));
                return children;
            })
            //3 排序
            .sorted((var1, var2) -> {
                return (var1.getSort() == null ? 0 : var1.getSort()) - (var2.getSort() == null ? 0 : var2.getSort());
            })
            //4 形成集合
            .collect(Collectors.toList());
    return collect;
}

 

posted @ 2020-07-20 00:22  鞋破露脚尖儿  阅读(212)  评论(0编辑  收藏  举报