1、entity
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class TutorialsCategory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
/**
* 上级类别(0表示一级分类)
*/
private Long superId;
/**
* 名称
*/
private String name;
/**
* 排序,数字越大的越靠后
*/
private Integer sortCategory;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}
2、vo
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class TutorialsCategoryTreeVo extends TutorialsCategory implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 设置树下级教程
*/
private List<TutorialsCategoryTreeVo> childTutorialsCategory=new ArrayList<>();
}
3、得到tree数据
@RequestMapping(value = "/getTutorialsCategoryTree",method = RequestMethod.POST)
@RequiresRoles(value={"SUPERMANAGER"},logical = Logical.OR)
public @ResponseBody
Object getTutorialsCategoryTree(HttpServletRequest request
){
List<TutorialsCategoryTreeVo> fisrtList=tutorialsService.selectTutorialsAllData(null);
List<TutorialsCategoryTreeVo> list=fisrtList.stream().filter(tutorialsCategoryTreeVo -> tutorialsCategoryTreeVo.getSuperId()==0L).map((menu)->{
menu.setChildTutorialsCategory(getChildrens(menu,fisrtList));
return menu;
}).collect(Collectors.toList());
Map<String,Object> map = new HashMap<String,Object>();
map.put("list",list);
return map;
}
private List<TutorialsCategoryTreeVo> getChildrens(TutorialsCategoryTreeVo root, List<TutorialsCategoryTreeVo> all) {
List<TutorialsCategoryTreeVo> childrenList = all.stream()
.filter(categoryVo -> categoryVo.getSuperId().intValue() == root.getId().intValue())
.map(categoryVo -> {
//子菜单可能还有子菜单, 因此递归查询,查询出子菜单 因为当前只有两级,所以不用
categoryVo.setChildTutorialsCategory(getChildrens(categoryVo, all));
return categoryVo;
}).collect(Collectors.toList());
return childrenList;
}
如果只有两级
private List<TutorialsCategoryTreeVo> getChildrens(TutorialsCategoryTreeVo root, List<TutorialsCategoryTreeVo> all) {
List<TutorialsCategoryTreeVo> cList=new ArrayList<>();
List<TutorialsCategoryTreeVo> childrenList = all.stream()
.filter(categoryVo -> categoryVo.getSuperId().intValue() == root.getId().intValue())
.map(categoryVo -> {
//子菜单可能还有子菜单, 因此递归查询,查询出子菜单 因为只有两级所以不需要
//categoryVo.setChildTutorialsCategory(getChildrens(categoryVo, all));
return categoryVo;
}).collect(Collectors.toList());
return childrenList;
}