目录
1 通过递归获取树形结构、通过父节点获取最底层节点(叶子节点)数据、树形XML,可以参考以下内容:
2 实体和数据结构
2.1 Dept实体类
2.2 相关树形结构
3 根据子节点获取最上层节点(根节点)数据
3.1 service层
3.2 controller层
3.3 测试
4 根据子节点获取所有上级集合
4.1 service层
4.2 controller层
4.3 测试
Java树形结构 根据父节点获取最底层节点数据 树形xml_www_48568302的博客-CSDN博客
/**
* @author W
* @createDate 2022/8/10
* @description: Dept实体类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {
private String id;
private String name;
private String parentId;
private List children = new ArrayList<>(); // 可不要
}
/**
* 根据子节点获取最上层节点
* @param deptAll 所有部门集合
* @param deptChild 子节点
* @return
*/
public static Dept getMaximumParent(List deptAll, Dept deptChild){
Dept dept = null;
String parentId = deptChild.getParentId();
if(parentId.equals("0")){
dept = deptChild;
}else {
List parent = deptAll.stream().filter(item -> item.getId().equals(parentId)).collect(Collectors.toList());
Dept maximumParent = getMaximumParent(deptAll, parent.get(0));
dept = maximumParent;
}
return dept;
}
/**
* 根据子节点获取最上层节点
* @param deptAll 所有部门集合
* @param deptChild 子节点
* @return
*/
public static Dept getMaximumParent2(List deptAll, Dept deptChild) {
if(ObjectUtil.isNotEmpty(deptChild)){
String parentId = deptChild.getParentId();
List parentDepts = deptAll.stream().filter(item -> item.getId().equals(parentId)).collect(Collectors.toList());
if(CollectionUtil.isNotEmpty(parentDepts)){
Dept parentDept = parentDepts.get(0);
Dept maximumParent2 = getMaximumParent2(deptAll, parentDept);
if(maximumParent2==null){
return parentDept;
}
return maximumParent2;
}
}
return null;
}
踩坑,通过索引获取空集合元素,会报IndexOutOfBoundsException下标越界异常,代码如下:
报错信息,如下:
@GetMapping("/getMaximumParent2")
public ResponseResult getMaximumParent2(){
List deptAll = GetLeafNode.getDeptAll(); // 所有部门集合
Dept leafNodeDept = new Dept("322","四层8","32",null);
Dept deptRoot = GetLeafNode.getMaximumParent2(deptAll, leafNodeDept);
return ResponseResult.success("根据子节点获取根节点",deptRoot);
}
/**
* 向上查询所有上级
* @param deptAll 所有集合
* @param leafNodeDept 叶子节点
*/
public static Set getDeptUpList(List deptAll,Dept leafNodeDept){
if(ObjectUtil.isNotEmpty(leafNodeDept)){
Set set = new HashSet<>();
String parentId = leafNodeDept.getParentId();
List parentDepts = deptAll.stream().filter(item -> item.getId().equals(parentId)).collect(Collectors.toList());
if(CollectionUtil.isNotEmpty(parentDepts)){
Dept parentDept = parentDepts.get(0);
set.add(parentDept);
Set deptUpTree = getDeptUpList(deptAll, parentDept);
if(deptUpTree!=null){
set.addAll(deptUpTree);
}
return set;
}
}
return null;
}
@GetMapping("/getDeptUpList")
public ResponseResult getDeptUpTree(){
List deptAll = GetLeafNode.getDeptAll(); // 所有部门集合
Dept leafNodeDept = new Dept("322","四层8","32",null);
Set deptUpTree = GetLeafNode.getDeptUpList(deptAll, leafNodeDept);
return ResponseResult.success("根据子节点查出的所有上级",deptUpTree);
}