1.实体
@Data
public class Menu {
//id
public Integer id;
//名称
public String name;
//父级id
public Integer parentId;
//子级集合
public List<Menu> childList;
public Menu(Integer id,String name,Integer parentId){
this.id = id;
this.name = name;
this.parentId = parentId;
}
}
2.controller
public void testMenuTree() {
List<Menu> menuDatas = getMenuData();
List<Menu> menuTree = menuDatas.stream().filter(m -> m.getParentId() == 0)
.map((m) -> {
m.setChildList(getChildrens(m, menuDatas));
return m;
}
).collect(Collectors.toList());
System.out.println("菜单树结构:" + JSONUtil.toJsonPrettyStr(menuTree));
}
/**
* 获取子类
* @param parent
* @param menuDatas
* @return
*/
private List<Menu> getChildrens(Menu parent, List<Menu> menuDatas) {
List<Menu> childList = menuDatas.stream().filter(m -> {
return Objects.equals(m.getParentId(), parent.getId());
}).map((m) -> {
m.setChildList(getChildrens(m, menuDatas));
return m;
}).collect(Collectors.toList());
return childList;
}