简易版

发布时间 2023-11-13 11:33:02作者: 指尖的键舞
public List<CategoryEntity> queryWithTree() {
//所有数据
    List<CategoryEntity> entityList = baseMapper.selectList(null);
    
    List<CategoryEntity> collect = entityList.stream().filter(item -> {
        return item.getParentCid() == 0; //过滤,找出所有没有父级的
    }).map(menu -> {
        menu.setChildList(getChildList(menu, entityList));//递归将设置子菜单
        return menu;
    }).sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : 
         item.getSort()))).collect(Collectors.toList());//排序
    return collect;
}

private List<CategoryEntity> getChildList(CategoryEntity menu, List<CategoryEntity> entityList) {

    List<CategoryEntity> collect = entityList.stream().filter(item -> {
        return item.getParentCid() == menu.getCatId();
    }).map(child -> {
        child.setChildList(getChildList(child, entityList));
        return child;
    }).sorted(Comparator.comparingInt(item -> (item.getSort() == null ? 0 : item.getSort()))).collect(Collectors.toList());
    return collect;
}