java递归生成树菜单
要给前端返回类似下面的json格式
[
{
"title": "一级1",
"id": 1,
"children": [
{
"title": "二级1-1",
"id": 3,
"children": [
{
"title": "三级1-1-3",
"id": 23
},
{
"title": "三级1-1-1",
"id": 7
},
{
"title": "三级1-1-2",
"id": 8,
"field": ""
}
]
}
]
}
]
Java 后端
1:利用mybatis的递归查询 ( 数据库查询比较浪费时间,之前文章有介绍,有兴趣查看之前的博客文章)
2:数据查询所有数据,代码递归生成对象(本次介绍的就是这种)
2.1 普通版
//源数据
List<VoMenu> list=menuService.findTreeMenuByRole(StringUtils.isEmpty(midList)?"":midList);
//递归生成的数据
List<VoMenu> newMenuList = new ArrayList<VoMenu>();
for (int i = 0; i < list.size(); i++) {
// 一级菜单pId=0
if (list.get(i).getPid().equals("0")) {
newMenuList.add(list.get(i));
}
}
for (VoMenu menu : newMenuList) {
//调用setTree 方法
menu.setChildren(setTree(""+menu.getId(), list));
}
setTree 方法
private List<VoMenu> setTree(String id,List<VoMenu> list) {
// 子菜单
List<VoMenu> childList = new ArrayList<>();
for (VoMenu menu : list) {
// 遍历所有节点,将父菜单id与传过来的id比较
if (menu.getPid().equals(id)) {
childList.add(menu);
}
}
// 把子菜单的子菜单再循环一遍
for (VoMenu menu : childList) {
menu.setChildren(setTree(""+menu.getId(), list));
}
if (childList.size() == 0) {
return Lists.newArrayList();
}
return childList;
}
2.2优化版
import com.alibaba.fastjson.JSON;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
public class CategoryUtil {
public CategoryUtil() {
}
public static List<VoMenu> buildTree(List<VoMenu> categoryInfos) {
List<VoMenu> collect = (List)categoryInfos.stream().filter((data) -> {
return Objects.isNull(data.getParentCategoryId());
}).collect(Collectors.toList());
collect.forEach((data) -> {
buildTree(data, categoryInfos);
});
return collect;
}
private static void buildTree(VoMenu vo, List<VoMenu> newlist) {
String id = vo.getId();
if (StringUtils.isEmpty(id)) {
throw new ServiceException(String.format("数据异常,data:%s", JSON.toJSON(vo)));
} else {
List<VoMenu> subList = (List)newlist.stream().filter((target) -> {
return Objects.nonNull(target.getPid()) && id.equals(target.getPid());
}).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(subList)) {
subList.forEach((subData) -> {
buildTree(subData, newlist);
});
vo.setChildren(subList);
}
}
}
}