多层级tree状数据优化

商品分类

在这里插入图片描述

domian

@TableName("t_product_type")
public class ProductType extends Model<ProductType> {
 	@TableId(value = "id", type = IdType.AUTO)
    private Long id;
    
     //父Id
    private Long pid;
    
    //子分类
    @TableField(exist = false)
    private List<ProductType> children =new ArrayList<>();
    ... ...
}

原方案:递归

1.先获取第一级菜单
2.准备递归的出口
3.递归调用
4.将获取的子菜单设置给父菜单

 /**
     * @param pid   一级菜单 pid = 0
     * @return
     */
    public List<ProductType> getAllChildren(Long pid) {
        Wrapper<ProductType> wrapper = new EntityWrapper<>();
        wrapper.eq("pid", pid);
        return productTypeMapper.selectList(wrapper);
    }
	/**
     * 递归函数
     * @param pid
     * @return
     */
    public List<ProductType> treeDataRecursion(Long pid) {
        List<ProductType> allChildren = getAllChildren(pid);

        //递归出口
        if (allChildren == null && allChildren.size() == 0) {
            return null;
        }

        for (ProductType children : allChildren) {
        	//递归调用
            List<ProductType> productTypes = treeDataRecursion(children.getId());
            //将子菜单设置给父菜单
            children.setChildren(productTypes);
        }
        return allChildren;
    }

	 @Override
    public List<ProductType> treeData() {
	    return treeDataRecursion(0L);
    }

优化方案:组合List集合数据结构

1.定义返回的结果集 List
2.获取所有菜单数据
3.将所有数据存进map集合中 key:Long id ,value:菜单对象
4.组装数据 (详见 :代码 )
5.返回结果集

public List<ProductType> treeDataLoop() {
        //最终返回的数据结构
        List<ProductType> result = new ArrayList<>();

        //所有的分类数据
        List<ProductType> allProductTypes = productTypeMapper.selectList(null);

        //把所有数据放进map中
        Map<Long,ProductType> map =new HashMap<>();
        for (ProductType pt : allProductTypes) {
            map.put(pt.getId(),pt);
        }

        //组装数据结构
        for (ProductType current : allProductTypes) {
            if(current.getPid()==0){
                //将一级菜单添加给结果集
                result.add(current);
            }else {
                //通过pid找到父级菜单
                ProductType parent = map.get(current.getPid());
                //将自己添加进父级菜单
                parent.getChildren().add(current);
            }
        }
        return result;
    }

	 @Override
    public List<ProductType> treeData() {
        return treeDataLoop();
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值