86 lines
2.6 KiB
Java
86 lines
2.6 KiB
Java
package com.zhgd.xmgl.util;
|
|
|
|
import org.apache.commons.lang3.StringUtils;
|
|
|
|
import java.lang.reflect.Field;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
/**
|
|
* 构建Tree
|
|
*/
|
|
public class TreeUtil {
|
|
|
|
/**
|
|
* 通过Map方式构建树
|
|
*
|
|
* @param list 列表
|
|
* @return {@link List}<{@link T}>
|
|
*/
|
|
public static <T> List<T> buildTreeByMap(List<T> list) {
|
|
return buildTreeByMap(list, "id", "parentId", "children", "0");
|
|
}
|
|
|
|
/**
|
|
* 通过Map方式构建树
|
|
*
|
|
* @param list 列表
|
|
* @param idName id名称
|
|
* @param parentIdName 父id名称
|
|
* @param childrenName 子节点列表名称
|
|
* @param topParentIdVal 顶层节点父id的值
|
|
* @return {@link List}<{@link T}>
|
|
*/
|
|
public static <T> List<T> buildTreeByMap(List<T> list, String idName, String parentIdName, String childrenName, Object topParentIdVal) {
|
|
if (StringUtils.isBlank(idName) || StringUtils.isBlank(parentIdName) || StringUtils.isBlank(childrenName)) {
|
|
return new ArrayList<>();
|
|
}
|
|
//根据parentId进行分组
|
|
Map<String, List<T>> mapList = list.stream().collect(Collectors.groupingBy(o -> getFieldValue(o, parentIdName).toString()));
|
|
//给每个节点设置子节点列表
|
|
list.forEach(node -> setFieldValue(node, mapList.get(getFieldValue(node, idName).toString()), childrenName));
|
|
return list.stream().filter(o -> topParentIdVal.equals(getFieldValue(o, parentIdName))).collect(Collectors.toList());
|
|
}
|
|
|
|
/**
|
|
* 获取属性值
|
|
*
|
|
* @param o 对象
|
|
* @param fieldName 属性名
|
|
* @return {@link String}
|
|
*/
|
|
private static Object getFieldValue(Object o, String fieldName) {
|
|
try {
|
|
Class<?> oClass = o.getClass();
|
|
Field field = oClass.getDeclaredField(fieldName);
|
|
field.setAccessible(true);
|
|
return field.get(o);
|
|
} catch (NoSuchFieldException | IllegalAccessException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 设置字段值
|
|
*
|
|
* @param o 对象
|
|
* @param val 值
|
|
* @param fieldName 属性名
|
|
*/
|
|
private static void setFieldValue(Object o, Object val, String fieldName) {
|
|
try {
|
|
Class<?> oClass = o.getClass();
|
|
Field field = oClass.getDeclaredField(fieldName);
|
|
field.setAccessible(true);
|
|
field.set(o, val);
|
|
} catch (NoSuchFieldException | IllegalAccessException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
|
|
|
|
}
|