stream流实现树形菜单

树形菜单用到的类
@Data
public class MenuTree {
private Integer id;

private String name;

private Integer parentId;

private List<MenuTree> children;
}
public List<MenuTree> getMenuTree(){
   // 讲其他类转化为menuTree 自行实现方法
List<MenuTree> menus = this.convertMenu(this.list());
   // 默认一级菜单的parentId为0
List<MenuTree> list = menus.stream().filter(menu -> menu.getParentId() == 0).peek(
menu -> menu.setChildren(getChildrens(menu, menus))
).collect(Collectors.toList());
return list;
}

// 递归查询
public List<MenuTree> getChildrens(MenuTree root,List<MenuTree> menus){
List<MenuTree> list = menus.stream().filter(menu ->
Objects.equals(menu.getParentId(), root.getId())).map(menu -> {
menu.setChildren(this.getChildrens(menu, menus));
return menu;
}).collect(Collectors.toList());
return list;
}
 
posted @ 2021-12-31 10:44  DarkerbeS  阅读(140)  评论(0编辑  收藏  举报