Java代码实现树节点和列表之间的相互转换
package com.example.test;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Student {
public static void main(String[] args) {
List<Student1> list = new ArrayList<>();
Student1 s1 = new Student1(1, "r1", 0);
Student1 s2 = new Student1(2, "r2", 1);
Student1 s3 = new Student1(3, "r3", 1);
Student1 s4 = new Student1(4, "r4", 2);
Student1 s5 = new Student1(5, "r5", 3);
Student1 s6 = new Student1(6, "r6", 5);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
Student1 rootNode = getRootNode(list);
System.out.println(rootNode);
Map<Integer, Student1> map = new HashMap<>();
fun1(rootNode, map);
List<Student1> collect = map.values().stream().peek(o -> o.setSon(new ArrayList<>())).collect(Collectors.toList());
System.out.println(collect);
}
public static void fun1(Student1 node, Map<Integer, Student1> map) {
if (CollectionUtils.isEmpty(node.getSon())) {
map.put(node.getId(), node);
return;
}
map.put(node.getId(), node);
for (Student1 student : node.getSon()) {
map.put(student.getId(), student);
fun1(student, map);
}
}
public static Student1 getRootNode(List<Student1> list) {
Map<Integer, Student1> student1Map = list.stream().collect(Collectors.toMap(Student1::getId, Function.identity()));
for (Student1 student1 : list) {
if (student1.getParentId() != 0) {
if (student1Map.get(student1.getParentId()).getSon() == null) {
student1Map.get(student1.getParentId()).setSon(new ArrayList<>());
}
student1Map.get(student1.getParentId()).getSon().add(student1);
}
}
return list.stream().filter(o -> o.getParentId() == 0).findFirst().get();
}
static class Student1 {
private int id;
private String name;
private int parentId;
public List<Student1> son;
@Override
public String toString() {
return "Student1{" + "id=" + id + ", name='" + name + '\'' + ", parentId=" + parentId + ", son=" + son + '}';
}
public Student1() {
}
public Student1(int id, String name, int parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public List<Student1> getSon() {
return son;
}
public void setSon(List<Student1> son) {
this.son = son;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
}
}