商品服务三级分类(1)---代码实现

商品服务三级分类(1)—代码实现

首先,先看一下效果图:

在这里插入图片描述

下面是数据库中存放的商品分类的分类的表

在这里插入图片描述

字段解释:

parent_cId:父分类的cat_id。

cat_level:分类的级别

sort:优先级,越小优先级越高

分析

因为分类之间具有父子关系,像一个树形结构,因此需要在分类这个bean类中添加一个属性,用于指向子分类。

	/**
	 * 子分类List集合
	 */
	@TableField(exist = false)
	private List<CategoryEntity> children;

为了形成树形结构,因此需要增加保存子分类的List集合,TableFiled(exist = false)作用是声明这个属性在数据库中不存在

代码实现

  • service:

    public List<CategoryEntity> listWithTree() {
          
          
            //1、查出所有分类
            List<CategoryEntity> entities = baseMapper.selectList(null);
            //2、组装成具有父子关系的树形结构(因为要形成树形结构,所以要有一个List的属性来存子分类)
            //2.1、找到所有一级分类(parentId == 0)
            List<CategoryEntity> level1Menus = entities.stream().filter(e ->
                    e.getParentCid() == 0
            ).map(e -> {
          
          
                //查找子分类
                e.setChildren(getChildrens(e,entities));
                return e;
            }).sorted((e1,e2) -> {
          
          
                //排序
                return (e1.getSort()==null?0:e1.getSort()) -(e2.getSort()==null?0:e2.getSort());
            }).collect(Collectors.toList());
            return level1Menus;
        }
    

  • 递归方法:

    /**
         * 递归地在所有分类中找到当前分类的子分类
         * @param currentMenu
         * @param all
         * @return
         */
        private List<CategoryEntity> getChildrens(CategoryEntity currentMenu,List<CategoryEntity> all) {
          
          
            //找到所有子分类并加入到子分类的List中
            List<CategoryEntity> children = all.stream().filter(e -> {
          
          
                return e.getParentCid().intValue() == currentMenu.getCatId().intValue();
            }).map(e -> {
          
          
                //继续找每个子分类的子分类
                e.setChildren(getChildrens(e,all));
                return e;
            }).sorted((e1,e2) -> {
          
          
                //排序
                return (e1.getSort()==null?0:e1.getSort()) -(e2.getSort()==null?0:e2.getSort());
            }).collect(Collectors.toList());
    
            return children;
        }
    

总结

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44829930/article/details/109511129