MySql数据库表结构
模拟数据
查询出所有数据,用父节点递归查询出所有子节点数据
/**
* 封装备注分类集合
*
* @param remarkTypeList 备注分类集合
* @return 递归好的集合
*/
@Override
public List<RemarkType> queryRemarkTypeList(List<RemarkType> remarkTypeList) {
Map<Long, List<RemarkType>> childrenMap = remarkTypeList.stream()
.filter(item -> Objects.equals("0", item.getDisplayStatus()))
.collect(Collectors.groupingBy(RemarkType::getParentId));
return getChildren(0L, childrenMap);
}
/**
* 递归查询子节点
*
* @param parentId 父id
* @param childrenMap 子节点Map
* @return 节点分类列表
*/
private List<RemarkType> getChildren(Long parentId, Map<Long, List<RemarkType>> childrenMap) {
return Optional.ofNullable(childrenMap.get(parentId))
.orElse(Collections.emptyList())
.stream()
.peek(item -> item.setChildren(getChildren(item.getRemarkTypeId(), childrenMap)))
.sorted(Comparator.comparingInt(item -> Optional.ofNullable(item.getSort()).orElse(0)))
.collect(Collectors.toList());
}
根据子节点查询所有父节点数据
/**
* 根据子节点查询全部父节点
*
* @param category 备注类型对象
* @return 节点集合
*/
@Override
public List<String> getParent(RemarkType category) {
List<String> types = new ArrayList<>();
//没到顶层节点就一直递归
if (category.getParentId() != 0L) {
RemarkType parentCategory = getById(category.getParentId());
types.addAll(getParent(parentCategory));
}
types.add(category.getTypeName());
return types;
}
标签:category,return,Stream,递归,List,item,Java,节点,childrenMap
From: https://www.cnblogs.com/Linzj5950/p/17778583.html