要么,这种,反复查数据库
public void test(){
System.out.println(JSON.toJSONString(findMenu(0)));
}
public List<Menu> findMenu(int x){
LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<>();
//查询条件
lqw.eq(Menu::getParentId, x);
List<Menu> list = menuService.list(lqw);
for (Menu menu : list) {
//递归子类数据
menu.setChildrenList(findMenu(menu.getId()));
}
return list;
}
要么就是,每次递归调用,都要传递整个查询数据。
@Test
public void TreeDemo(){
List<Menu> allList = menuService.list();
List<Menu> collect = allList.stream()
.filter(item -> item.getParentId() == 0)
.map(item -> {
item.setChildrenList(getChildren(item.getId(), allList));
return item;
}).
collect(Collectors.toList());
System.out.println(new Gson().toJsonTree(collect));
}
public List<Menu> getChildren(int id, List<Menu> allList) {
List<Menu> collect = allList.stream()
.filter(item -> item.getParentId().equals(id))
.map(item -> {
item.setChildrenList(getChildren(item.getId(), allList));
return item;
})
.collect(Collectors.toList());
return collect;
}