1、先把數(shù)據(jù)插入到數(shù)據(jù)庫(kù)详炬、pms_category文件
2梨水、在Category控制層中查詢赋铝、service層中寫對(duì)應(yīng)方法
????/**
*查出所有分類以及子類泼菌,以樹狀結(jié)構(gòu)組裝起來(lái)
?????*/
????@RequestMapping("/list/tree")
????public R list(){
????????List<CategoryEntity> entities = categoryService.listWithTree();
????????return R.ok().put("data", entities);
????}
3、在category的實(shí)體類中 加入子菜單屬性
4琅关、在Impl層中實(shí)現(xiàn)具體方法
?@Override
????public List<CategoryEntity> listWithTree() {
//1煮岁、獲取所有l(wèi)ist內(nèi)容
????????List<CategoryEntity> entities = baseMapper.selectList(null);
//2、組裝成樹狀結(jié)構(gòu)
//2.1找到一級(jí)分類 ?使用stream().filter()過濾涣易,過濾categoryEntity中ParentCid=0的画机,把它選出來(lái)并使用collect toList使用list集合收集
// ???????List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
// ???????????return categoryEntity.getParentCid() == 0;
// ???????}).collect(Collectors.toList());
????????List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
????????????return categoryEntity.getParentCid() == 0;
}).map((menu)->{//每一個(gè)菜單
menu.setChildren(getChildrens(menu, entities));//將子類菜單賦給menu并返回過去——子菜單如何獲得?通過遞歸獲取子菜單
????????????return menu;
????????}).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
????????????????.collect(Collectors.toList());
????????return level1Menus;
????}
遞歸函數(shù)查詢下一級(jí)的子菜單
//遞歸方法 返回子菜單 遞歸查找所有菜單的子菜單
private List getChildrens(CategoryEntity root, List all){//傳入當(dāng)前菜單CategoryEntity 以及 所有菜單List<CategoryEntity>都毒,在all中找到root
????????List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == root.getCatId(); //過濾:選取這個(gè)菜單的父節(jié)點(diǎn)等于root(當(dāng)前菜單)的id并返回
????????}).map((categoryEntity)->{
//1色罚、找到子菜單
categoryEntity.setChildren(getChildrens(categoryEntity, all));//還是需要找到子菜單,使用遞歸
????????????return categoryEntity;
????????}).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
????????????????.collect(Collectors.toList());
????????return children;
????}