【文件属性】:
文件名称:java树形结构递归查询
文件大小:2KB
文件格式:MD
更新时间:2021-09-24 11:10:48
java 树形结构查询
/**
* 根据等级查询类目树
*
* @param level
* @return
*/
@Override
public List queryCategoryTree(Integer level) {
//查询当前级别下类目
List list = categoryDAO.list(level);
//组装好的类目树,返回前端
List categoryTree = new ArrayList<>();
//所有类目
List allDTOList = new ArrayList<>();
if (CollectionUtils.isEmpty(list)) {
return categoryTree;
}
for (CategoryDO categoryDO : list) {
allDTOList.add(new CategoryTreeDTO().convertDOToDTO(categoryDO));
}
//当前等级类目
categoryTree = allDTOList.stream().filter(dto -> level.equals(dto.getLevel())).collect(Collectors.toList());
for (CategoryTreeDTO categoryTreeDTO : categoryTree) {
//组装类目为树结构
assembleTree(categoryTreeDTO, allDTOList,Constants.CATEGORY_MAX_LEVEL - level);
}
return categoryTree;
}
/**
* 组装树
*
* @param categoryTreeDTO
* @param allList
* @param remainRecursionCount 剩余递归次数
* @return
*/
public CategoryTreeDTO assembleTree(CategoryTreeDTO categoryTreeDTO, List allList, int remainRecursionCount) {
remainRecursionCount--;
//最大递归次数不超过Constants.CATEGORY_MAX_LEVEL-level次,防止坏数据死循环
if(remainRecursionCount < 0){
return categoryTreeDTO;
}
String categoryCode = categoryTreeDTO.getCategoryCode();
Integer level = categoryTreeDTO.getLevel();
//到达最后等级树返回
if (Constants.CATEGORY_MAX_LEVEL == level) {
return categoryTreeDTO;
}
//子类目
List child = allList.stream().filter(a -> categoryCode.equals(a.getParentCode())).collect(Collectors.toList());
if (null == child) {
return categoryTreeDTO;
}
categoryTreeDTO.setChildren(child);
//组装子类目
for (CategoryTreeDTO dto : child) {
assembleTree(dto, allList,remainRecursionCount);
}
return categoryTreeDTO;
}