给定一个list,根据id和pid生成树结构
给定一个list,根据id和pid生成树结构
原始数据处理
//原始数据
List<ContractListingDetailinfoVO> list = contractListingDetailinfoDao.queryListingsDetailListByListingId(params);
//根数据
List<ContractListingDetailinfoVO> roots = list.stream().filter(o -> o.getPid() == null).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(roots)){
//除去根数据 减少数据处理
list.removeAll(roots);
//拼成树的结构
this.fillTree(roots,list);
}
//roots就是生成的树结构
递归处理 生成tree
/**
* //拼成树的结构
* @param roots
* @param list
*/
/**
* 根据根节点,去遍历子节点。获取最终tree结构
*
*/
private void fillTree(List<ContractListingDetailinfoVO> rootOrgDateList, List<ContractListingDetailinfoVO> orgDateDtoVoList) {
for (ContractListingDetailinfoVO orgDtoVo : rootOrgDateList) {
//获取父节点的子集
List<ContractListingDetailinfoVO> children = fillChildren(orgDtoVo, orgDateDtoVoList);
if (CollectionUtils.isEmpty(children)) {
continue;
}
//子集不为空的话 递归 继续往下遍历
orgDateDtoVoList.removeAll(children);
fillTree(children, orgDateDtoVoList);
}
}
/**
* 根据父节点id,去遍历子节点(parentId),将子节点的结果set到父节点的Children。获取最终tree结构
*
*/
private List<ContractListingDetailinfoVO> fillChildren(ContractListingDetailinfoVO parent, List<ContractListingDetailinfoVO> orgDateDtoVoList) {
List<ContractListingDetailinfoVO> childrenList = new ArrayList<>();
for (ContractListingDetailinfoVO dtoVo : orgDateDtoVoList) {
if (parent.getId().equals(dtoVo.getPid())) {
childrenList.add(dtoVo);
if (parent.getChild() == null) {
parent.setChild(new ArrayList<ContractListingDetailinfoVO>());
}
parent.getChild().add(dtoVo);
}
}
return childrenList;
}