public class TreeUtil {
/**
* @Description: 首字母转大写
*/
public static String firstCharToUpperCase(String str){
if(str == null){ return null; }
if("".equals(str)){ return ""; }
char[] cs = str.toCharArray();
cs[0]-=32;
return String.valueOf(cs);
}
/** 调用示例:示例: List<TreeNode> head = toTree(TreeNode.class,nodeList,"id","parentId","children",0L);
* @Description: List转Tree
* @param clazz 类.class
* @param dataList 数据列表
* @param idField ID字段名称
* @param parentIdField 父节点ID字段名称
* @param childrenField 孩子字段名称
* @param rootFlag 如果某个节点的ParentId等于rootFlag,即改节点为根节点
*/
public static <T> List<T> toTree(Class<T> clazz,List<T> dataList,String idField,String parentIdField,String childrenField,Object rootFlag) throws Exception {
List<T> treeList = new ArrayList<>();
Map<Object,T> map = new HashMap<>();
Map<Object,Boolean> flag = new HashMap<>();
String getIdStr = "get"+firstCharToUpperCase(idField);
String getParentIdStr = "get"+firstCharToUpperCase(parentIdField);
String getChildrenStr = "get"+firstCharToUpperCase(childrenField);
String setChildrenStr = "set"+firstCharToUpperCase(childrenField);
Method getIdMethod = null;
Method getParentIdMethod=null;
Method getChildrenMethod=null;
Method setChildrenMethod=null;
try{
getIdMethod = clazz.getDeclaredMethod(getIdStr);
getParentIdMethod = clazz.getDeclaredMethod(getParentIdStr);
getChildrenMethod = clazz.getDeclaredMethod(getChildrenStr);
setChildrenMethod = clazz.getDeclaredMethod(setChildrenStr,List.class);
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException("转树形结构-通过反射获取方法错误!",e);
}
for(T node:dataList){
map.put(getIdMethod.invoke(node),node);
Object parentIdTmp = getParentIdMethod.invoke(node);
if(rootFlag==null || "".equals(rootFlag)){
if(parentIdTmp==null || "".equals(parentIdTmp)){
treeList.add(node);
}
}else{
if(String.valueOf(rootFlag).equals(String.valueOf(parentIdTmp))){
treeList.add(node);
}
}
}
for(T node:dataList){
T parentNode = map.get(getParentIdMethod.invoke(node));
if(parentNode!=null){
List<T> invoke = (List<T>)getChildrenMethod.invoke(parentNode);
if(invoke==null){
invoke=new ArrayList<>();
setChildrenMethod.invoke(parentNode,invoke);
}
invoke.add(node);
}
}
return treeList;
}
}
``