N级树形菜单封装

N级树形菜单封装

每次遇到这样的需求,虽然能写出来,但是每次还是要费一点脑细胞,写了一个复用性强的,方便以后

//分类菜单的树形结构封装
@Override
public List<CategoryEntity> categoryList() {
    //一次查询得到所有的菜单项
    List<CategoryEntity> list = categoryDao.selectList(null);
    List<CategoryEntity> categoryEntities = listToTree(list);
    return categoryEntities;
}
​
//封装树形结构
public List<CategoryEntity> listToTree(List<CategoryEntity> list){
    //树形结构集合
    List<CategoryEntity> tree = new ArrayList<>();
    for (CategoryEntity categoryEntity : list) {
        //首先只对一级菜单进行封装
        if (categoryEntity.getParentCid() == 0){
            tree.add(getTree(categoryEntity, list));
        }
    }
    return tree;
}
​
//递归封装树形菜单 root:当前主菜单
public CategoryEntity getTree(CategoryEntity root,List<CategoryEntity> all){
    all.forEach(category -> {
        if (category.getParentCid() == root.getCatId()){
            if (root.getChildren() == null){
                root.setChildren(new ArrayList<CategoryEntity>());
            }
            //递归封装子节点
            root.getChildren().add((CategoryEntity) getTree(category, all));
        }
    });
    return root;
}

.

原文地址:https://www.cnblogs.com/msi-chen/p/13342190.html