**前言:**开发中经常遇到同一张表里面的数据需要通过id和parent_id进行层级处理,这里提供递归处理的代码示例。
public static List<CaseReasonTreeVo> listToTree(List<CaseReasonTreeVo> list) {
//用递归找子。
List<CaseReasonTreeVo> treeList = new ArrayList<>();
for (CaseReasonTreeVo tree : list) {
if (StringUtils.isEmpty(tree.getParentId()) || "-1".equals(tree.getParentId())) {
treeList.add(findChildren(tree, list));
}
}
return treeList;
}
private static CaseReasonTreeVo findChildren(CaseReasonTreeVo tree, List<CaseReasonTreeVo> list) {
for (CaseReasonTreeVo node : list) {
if (tree.getId().equals(node.getParentId())) {
if (null == tree.getSubs()) {
tree.setSubs(new ArrayList<>());
}
node.setDeep(tree.getDeep() + 1);
CaseReasonTreeVo indexVo = findChildren(node, list);
boolean hasMe=false;
for (CaseReasonTreeVo sub : tree.getSubs()) {
if(sub.getId().equals(indexVo.getId())){
hasMe =true;
break;
}
}
if(!hasMe){
tree.getSubs().add(indexVo);
}
}
}
return tree;
}