本文共 1809 字,大约阅读时间需要 6 分钟。
使用springboot+mybatis实现
1、controller@RequestMapping("/list/tree") @ApiOperation(value = "查询三级分类、组装为分类树",notes = "前端通过key==data获取") public R list(){ Listentities = categoryService.listWithTree(); return R.ok().put("data", entities); }
2、service
/** * 组装分类树 * * @return */@Overridepublic ListlistWithTree() { //1、查出所有分类数据 List entities = baseMapper.selectList(null); //2、组装成父子的树形结构 //2.1、找到所有的一级分类 List level1Menus = entities.stream() //过滤、拿到所有一级分类 .filter(categoryEntity -> categoryEntity.getParentCid() == 0) //映射、得到所有子分类然后存到children集合内 .map((menu) -> { menu.setChildren(getChildrens(menu, entities)); return menu; }) //排序、进行非空校验并升序排列 .sorted((menu1, menu2) -> { return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()); }) //收集组装集合 .collect(Collectors.toList()); return level1Menus;}/** * 为所有的父分类找到他的子分类并映射到child集合里、 * * @param root 父分类 * @param all 原始集合数据 * @return */private List getChildrens(CategoryEntity root, List all) { List children = all.stream() //root为父分类、得到所有分类的父Id == root分类Id的数据 .filter(categoryEntity -> { return categoryEntity.getParentCid() == 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 children;}
转载地址:http://yonti.baihongyu.com/