【项目笔记】三级分类:递归树形结构数据

注意要熟悉 stream 写法

@Override
public List<CategoryEntity> listWithTree() {
    //1.查出所有分类
    List<CategoryEntity> entities = baseMapper.selectList(null);

    List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) ->
                                                                categoryEntity.getParentCid() == 0
                                                               ).map((menu) -> {
        menu.setChildren(getChildrens(menu, entities));
        return menu;
    }).sorted((o1, o2) -> {
        return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
    }).collect(Collectors.toList());

    //2.组装成父子树形结构

    return level1Menus;
}

//递归查找所有菜单的子菜单
private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
    List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
        return categoryEntity.getParentCid().equals(root.getCatId());
    }).map(categoryEntity -> {
        //1.找到子菜单
        categoryEntity.setChildren(getChildrens(categoryEntity, all));
        return categoryEntity;
    }).sorted((o1, o2) -> {
        //2.菜单的排序
        return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
    }).collect(Collectors.toList());
    return children;
}

//for循环拼接

@Override
public List<CategoryEntity> listWithTree() {

    // 1.查询出所有的分类
    List<CategoryEntity> entities = baseMapper.selectList(null);

    // 2.组装成父子的树形结构

    List<CategoryEntity> level1Menus = new ArrayList<>();
    // 找到所有的一级分类
    for (CategoryEntity entity : entities) {
        if (entity.getParentCid() == 0) {
            level1Menus.add(entity);
        }
    }

    for (CategoryEntity level1Menu : level1Menus) {
        level1Menu.setChildren(getChildrens(level1Menu, entities));
    }
    //排序
    level1Menus.sort(new Comparator<CategoryEntity>() {
        @Override
        public int compare(CategoryEntity o1, CategoryEntity o2) {
            return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
        }
    });
    return level1Menus;
}

/**
     * 递归查找所有的下级分类
     * 在这一级别的分类中找下级分类
     *
     * @param root 当前级别的分类
     * @param all  全部分类
     * @return 下一级分类
     */
private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
    List<CategoryEntity> children = new ArrayList<>();
    for (CategoryEntity a : all) {
        if (a.getParentCid().equals(root.getCatId())) {
            a.setChildren(getChildrens(a, all));
            children.add(a);
        }
    }
    children.sort(new Comparator<CategoryEntity>() {
        @Override
        public int compare(CategoryEntity o1, CategoryEntity o2) {
            return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
        }
    });
    return children;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

跨域问题 上一篇
【项目笔记】VUE复习 下一篇