根据id名称和父id名称构建树结构
package diit.platform.bussiness.utils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TreeUtils {
public static <T> List<T> buildTree(String idName, String parentIdName, List<T> dataList) throws Exception {
// 创建一个 Map,用来存储 id 到数据对象的映射
Map<Object, T> dataMap = new HashMap<>();
for (T data : dataList) {
Field idField = data.getClass().getDeclaredField(idName);
idField.setAccessible(true);
Object idValue = idField.get(data);
dataMap.put(idValue, data);
}
// 创建一个 List,用来存储树的根节点
List<T> rootList = new ArrayList<>();
for (T data : dataList) {
Field parentIdField = data.getClass().getDeclaredField(parentIdName);
parentIdField.setAccessible(true);
Object parentIdValue = parentIdField.get(data);
if (parentIdValue == null || "".equals(parentIdValue.toString())) {
// 如果 parentId 为 null 或者为空字符串,那么这个节点是根节点
rootList.add(data);
} else {
// 否则,这个节点是某个已存在节点的子节点
T parentData = dataMap.get(parentIdValue);
if (parentData != null) {
Field childrenField = parentData.getClass().getDeclaredField("children");
childrenField.setAccessible(true);
List<T> childrenList = (List<T>) childrenField.get(parentData);
if (childrenList == null) {
childrenList = new ArrayList<>();
childrenField.set(parentData, childrenList);
}
childrenList.add(data);
}
}
}
return rootList;
}
}