一、获取所有分类上下级信息
/**
* 获取所有分类上下级信息
*/
public R<List<ResearchTypeTreeVO>> getTypeTreeList(){
//获取所有分类数据
List<ResearchTypeVO> list = ibResearchTypeService.getSuperList(null);
List<ResearchTypeTreeVO> researchTypeTreeVOList = null;
if(CollectionUtil.isNotEmpty(list)){
researchTypeTreeVOList = buildMenuTrees(list);
}
return R.data(researchTypeTreeVOList);
}
二、构建数据
public static List<ResearchTypeTreeVO> buildMenuTrees(List<ResearchTypeVO> list) {
if(CollectionUtils.isEmpty(list)){
return new ArrayList<>();
}
Map<Long, ResearchTypeVO> researchTypeVOMap = list.stream().collect((Collectors.toMap(ResearchTypeVO::getId, item -> item, (o, n) -> o)));
//上级数据
List<ResearchTypeTreeVO> parentList = new ArrayList<>();
List<ResearchTypeTreeVO> childList = new ArrayList<>();
for (ResearchTypeVO vo : list) {
long parentId = vo.getSuperId();
ResearchTypeTreeVO option = new ResearchTypeTreeVO();
option.setId(vo.getId());
option.setSuperId(parentId);
option.setSuperName(vo.getSuperName());
option.setLabel(vo.getTypeName());
option.setValue(vo.getTypeCode());
// 尝试查找父菜单项,如果不存在则dictBiz是顶级菜单项
ResearchTypeVO researchTypeVO = researchTypeVOMap.get(parentId);
if(Objects.isNull(researchTypeVO)){
parentList.add(option);
}else {
childList.add(option);
}
}
//对查询出来的菜单进行整理 整理为树状
sortMenu(parentList, childList);
return parentList;
}
三、递归
private static void sortMenu(List<ResearchTypeTreeVO> parentList, List<ResearchTypeTreeVO> childMenus) {
for (ResearchTypeTreeVO parent : parentList) {
List<ResearchTypeTreeVO> children = childMenus.stream()
.filter(child -> child.getSuperId().equals(parent.getId()) )
.collect(Collectors.toList());
// 设置父节点的子节点列表
parent.setChildren(children);
// 如果子节点列表不为空,则递归地对子节点进行排序
if (!children.isEmpty()) {
sortMenu(children, childMenus);
}
}
}