根据查询出来的一条条数据构建一棵树
public List<CoCommDictVO> getTreeByDictId(String dictId) throws CommonException{
List<CoCommDictVO> tree = null;
if (StringUtils.isNotEmpty(dictId)) {
List<CoCommDictVO> treeList = this.baseMapper.getTreeByDictId(dictId);
tree = DictService.buildTree(treeList, treeList.get(0).getParentId());
} else {
throw new CommonException("节点为空!");
}
return tree;
}
/**
* 将列表遍历为树形结构
* @param list 列表数据
* @param dictId 父节点ID,用于指定根节点
* @return 树形结构数据
*/
public static List<CoCommDictVO> buildTree(List<CoCommDictVO> list, String dictId) {
List<CoCommDictVO> treeList = new ArrayList<>();
for (CoCommDictVO node : list) {
if (dictId.equals(node.getParentId())) {
treeList.add(node);
}
}
for (CoCommDictVO node : treeList) {
node.setChildren(buildTree(list, node.getDictId()));
}
return treeList;
}