每当我们有构建树结构的需求时 写起来很麻烦,Steam流提供了一些构建树结构的api
ps: 如果不懂Steam流的请学习Steam流 这么不多介绍
废话不说上代码
List<CityVO> provinceList = dsCityInfoMapper.queryAgentProvince(agentId);
List<CityVO> districtList = dsCityInfoMapper.queryAgentDistrict(agentId, cityIds);
for (CityVO info : provinceList) {
// 取出根节点判断
for (CityVO cityInfo:info.getChildren()) {
cityInfo.setChildren(this.getChildrenList(cityInfo, districtList));
}
}
/**
* 递归查询分类子节点
* @param rootNode 根节点
* @param dataList 所有节点 根节点信息
*/
private List<CityVO> getChildrenList(CityVO rootNode, List<CityVO> dataList) {
return dataList.stream()
.filter(currentNode -> Objects.equals(currentNode.getPId(), rootNode.getId()))
.peek((currentNode) -> currentNode.setChildren(getChildrenList(currentNode, dataList)))
.sorted(Comparator.comparing(CityVO::getCreateTime).reversed())
.collect(Collectors.toList());
}