测试实体
@Data
public class Users {
private int id;
private int parentId;
// 子节点数据
private List<Users> child;
public Users() {
}
public Users(int id, int parentId) {
this.id = id;
this.parentId = parentId;
}
@Override
public String toString() {
return "Users{" +
"id=" + id +
", parentId=" + parentId +
", child=" + child +
'}';
}
}
实现功能的代码
public class TestTree {
public static void main(String[] args) {
List<Users> list = new ArrayList<>();
extracted(list);
List<Users> results = new ArrayList<>();
// 先获取一级节点
List<Users> collect = list.stream().filter(v -> v.getParentId() == -1).collect(Collectors.toList());
for (Users users : collect) {
List<Users> childNodes = buildChildNode(users, list);
users.setChild(childNodes);
results.add(users);
}
System.out.println(results);
}
private static List<Users> buildChildNode(Users users, List<Users> list) {
List<Users> childNodes = new ArrayList<>();
int id = users.getId();
List<Users> collect = list.stream().filter(v -> v.getParentId() == id).collect(Collectors.toList());
if (collect == null || collect.size() == 0) {
return childNodes;
}
for (Users users1 : collect) {
childNodes.add(users1);
List<Users> list1 = buildChildNode(users1, list);
if (list1 != null && list1.size() > 0) {
users1.setChild(list1);
}
}
return childNodes;
}
/**
获取测试数据
*/
private static void extracted(List<Users> list) {
Users users1 = new Users(1, -1);
list.add(users1);
Users users11 = new Users(11, 1);
list.add(users11);
Users users12 = new Users(12, 1);
list.add(users12);
Users users2 = new Users(2, -1);
list.add(users2);
Users users21 = new Users(21, 2);
list.add(users21);
Users users22 = new Users(22, 2);
list.add(users22);
Users users211 = new Users(211, 21);
list.add(users211);
Users users212 = new Users(212, 21);
list.add(users212);
Users users3 = new Users(3, -1);
list.add(users3);
}
}