Category类
@Data
@Builder
public class Category {
private int id;
private int parentId;
private String name;
private List<Category> children;
}
TreeUtils类
public class TreeUtils {
public static void main(String[] args) throws Exception {
List<Category> nodes = new ArrayList<Category>();
nodes.add(Category.builder().id(1).parentId(0).name("电脑").build());
nodes.add(Category.builder().id(2).parentId(1).name("dell").build());
nodes.add(Category.builder().id(3).parentId(1).name("mac").build());
nodes.add(Category.builder().id(4).parentId(2).name("pro").build());
List<Category> list = generate(nodes, 0);
System.out.println(JSONUtil.toJsonPrettyStr(list));
}
public static <T> List<T> generate(List<T> nodes, int parentId)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
return generate(nodes, 0, null, null, null);
}
public static <T> List<T> generate(List<T> nodes, int parentId, String idName, String pidName, String childrenName)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
if (StringUtils.isEmpty(idName)) {
idName = "id";
}
if (StringUtils.isEmpty(pidName)) {
pidName = "parentId";
}
if (StringUtils.isEmpty(childrenName)) {
childrenName = "children";
}
if (nodes == null || nodes.size() <= 0) {
// return Collections.emptyList();
return null;
}
List<T> list = new ArrayList<T>();
for (T node : nodes) {
Class<? extends Object> clazz = node.getClass();
Field idField = clazz.getDeclaredField(idName);
Field pidField = clazz.getDeclaredField(pidName);
Field childrenField = clazz.getDeclaredField(childrenName);
idField.setAccessible(true);
pidField.setAccessible(true);
childrenField.setAccessible(true);
int id = idField.getInt(node);
int pid = pidField.getInt(node);
if (pid == parentId) {
list.add(node);
List<T> children = generate(nodes, id, idName, pidName, childrenName);
childrenField.set(node, children);
}
}
return list;
}
}