递归遍历树节点
返回的数据结构符合element次级下拉选和树形控件:
数据库数据示例:parent_code指向父节点,area_type为节点等级
将查询到的结果集以List<Trees>格式查出调用getAllNodes()方法,Trees对象属性见下
/**
*
* @param allList 将要遍历成树型结构的集合以Trees对象的形式传入
* @return 返回封装好的List<Trees> 集合方便前端取出渲染
*/
public static List<Trees> getAllNodes(List<Trees> allList) {
List<Trees> parentList = new ArrayList<>();
for (int i = 0; i < allList.size(); i++) {
if("0".equals(allList.get(i).getParentCode())) {
parentList.add(allList.get(i));
allList.remove(i);
i--;
}
}
return getChildNodes(allList, parentList);
}
public static List<Trees> getChildNodes(List<Trees> allList, List<Trees> parentList) {
for (int i = 0; i < parentList.size(); i++) {
List<Trees> nodes = new ArrayList<>();
for (int j = 0; j < allList.size(); j++) {
if(parentList.get(i).getId().equals(allList.get(j).getParentCode())) {
nodes.add(allList.get(j));
allList.remove(j);
j--;
}
}
if(nodes.size() > 0) {
parentList.get(i).setChildren(nodes);
getChildNodes(allList, nodes);
}
}
return parentList;
}
Trees对象结构
// 编码
private String id;
// 父节点code
private String parentCode;
// 当前节点名称
private String label;
// 区域节点类型|节点等级
private String areaType;
// 子节点
private List<Trees> children;