五、获取树形结构数据递归写法

1、mysql库表字段
学习:构建表结构时的规范,字段类型的选择

CREATE TABLE `pms_category` (
  `cat_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '分类id',
  `name` char(50) DEFAULT NULL COMMENT '分类名称',
  `parent_cid` bigint(20) DEFAULT NULL COMMENT '父分类id',
  `cat_level` int(11) DEFAULT NULL COMMENT '层级',
  `show_status` tinyint(4) DEFAULT NULL COMMENT '是否显示[0-不显示,1显示]',
  `sort` int(11) DEFAULT NULL COMMENT '排序',
  `icon` char(255) DEFAULT NULL COMMENT '图标地址',
  `product_unit` char(50) DEFAULT NULL COMMENT '计量单位',
  `product_count` int(11) DEFAULT NULL COMMENT '商品数量',
  PRIMARY KEY (`cat_id`),
  KEY `parent_cid` (`parent_cid`)
) ENGINE=InnoDB AUTO_INCREMENT=1433 DEFAULT CHARSET=utf8mb4 COMMENT='商品三级分类';

从表可以得到通过parent_cid这个字段将整个数据结构串联在一起的
在这里插入图片描述
2、通过java代码获取并构建树形结构数据返回
可以在实际开发中借鉴使用
1)运用java8使用了Stream()的高级写法,并使用sorted()排序

public List<CategoryEntity> listWithTree() {
        // 1、查询所有数据
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 2、查询子集
        List<CategoryEntity> collect = entities.stream()
                .filter(category -> category.getParentCid() == 0)
                .map(categoryEntity -> {
                            categoryEntity.setChildren(getChildrens(categoryEntity, entities));
                            return categoryEntity;
                        }
                ).sorted((menu1, menu2) -> {
                            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                        }
                ).collect(Collectors.toList());

        return collect;
    }

2)递归获取子级信息

public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> collect = all.stream().filter(category -> category.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                            categoryEntity.setChildren(getChildrens(categoryEntity, all));
                            return categoryEntity;
                        }
                ).sorted((menu1, menu2) -> {
                            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                        }
                ).collect(Collectors.toList());
        return collect;

3)测试
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值