人狠话不多直接上代码
@Override
public List<Category> listWithTree() {
List<Category> categoryList = categoryMapper.selectCategoryList(null);
Map<Long, List<Category>> categoryMap = new HashMap<>();
for (Category category : categoryList) {
Long parentId = category.getParentId();
if (parentId == null) {
parentId = 0L;
}
categoryMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(category);
}
List<Category> rootCategories = categoryMap.get(0L);
if (rootCategories != null) {
for (Category rootCategory : rootCategories) {
buildCategoryTree(rootCategory, categoryMap);
}
}
return rootCategories;
}
private void buildCategoryTree(Category category, Map<Long, List<Category>> categoryMap) {
List<Category> children = categoryMap.get(category.getCategoryId());
if (children != null) {
for (Category child : children) {
buildCategoryTree(child, categoryMap);
}
}
category.setCategory(children);
}
注意!!!记得在自己的实体类中加一个List<类本身> XXXX 字段