Java将List年级班级课程转为树形结构
时间: 2023-10-29 11:41:15 浏览: 83
您可以使用递归算法将List年级、班级和课程数据转换为树形结构。以下是一个示例代码:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TreeNode {
private String name;
private List<TreeNode> children;
public TreeNode(String name) {
this.name = name;
this.children = new ArrayList<>();
}
public String getName() {
return name;
}
public List<TreeNode> getChildren() {
return children;
}
public void addChild(TreeNode child) {
children.add(child);
}
}
public class Main {
public static void main(String[] args) {
// 生成样例数据
Map<String, List<String>> gradeData = new HashMap<>();
gradeData.put("Grade 1", List.of("Class A", "Class B"));
gradeData.put("Grade 2", List.of("Class C", "Class D"));
gradeData.put("Grade 3", List.of("Class E"));
Map<String, List<String>> classData = new HashMap<>();
classData.put("Class A", List.of("Math", "Science"));
classData.put("Class B", List.of("English"));
classData.put("Class C", List.of("History", "Geography"));
classData.put("Class D", List.of("Physics", "Chemistry"));
classData.put("Class E", List.of("Art"));
// 转换为树形结构
TreeNode root = new TreeNode("School");
for (String grade : gradeData.keySet()) {
TreeNode gradeNode = new TreeNode(grade);
root.addChild(gradeNode);
List<String> classes = gradeData.get(grade);
for (String className : classes) {
TreeNode classNode = new TreeNode(className);
gradeNode.addChild(classNode);
List<String> courses = classData.get(className);
for (String course : courses) {
TreeNode courseNode = new TreeNode(course);
classNode.addChild(courseNode);
}
}
}
// 打印树形结构
printTree(root, 0);
}
private static void printTree(TreeNode node, int depth) {
StringBuilder indent = new StringBuilder();
for (int i = 0; i < depth; i++) {
indent.append(" ");
}
System.out.println(indent + node.getName());
for (TreeNode child : node.getChildren()) {
printTree(child, depth + 1);
}
}
}
```
以上示例代码将List年级、班级和课程数据转换为一个树形结构,并打印出来。您可以根据实际情况修改数据结构和打印方式。
阅读全文