我有一个文本文件,其中包含一组记录,如下所示:
START
PARENT1 dataX dataY
CHILD1 dataA dataB
CHILD2 dataC DataD
PARENT2 dataJ dataK
CHILD1 dataE dataF
END
我想创建一个List对象。每个家长都应将所有子对象作为一个列表。
答案 0 :(得分:1)
这里是让List
个有孩子的父母的方法。我定义了类Parent
和Child
。 Parent
有子级-定义为集合List<Child>
。该程序遍历输入文件的各行并处理每一行。定义为静态变量的外部集合List<Parent>
存储所有父项。
示例程序:
import java.util.*;
import java.nio.file.*;
import java.io.IOException;
public class ComplexObjects {
private static List<Parent> parents;
private static Parent parent;
private static boolean startFlag;
public static void main(String [] args) throws IOException {
Path path = Paths.get("complex_data.txt");
Files.lines(path)
.peek(System.out::println)
.forEach(line -> processLine(line));
System.out.println(parents);
}
private static void processLine(String line) {
if (line.startsWith("START")) {
startFlag = true;
parents = new ArrayList<Parent>();
}
else if (line.startsWith("PARENT")) {
// store the parent with children
// create a new parent
if (startFlag) {
startFlag = false;
}
else {
parents.add(parent);
}
parent = new Parent(line);
}
else if (line.startsWith("CHILD")) {
// create a new child
// add to the parent
String [] tokens = line.split(" ");
parent.addChild(new Child(tokens[0], tokens[1], tokens[2]));
}
else if (line.startsWith("END")) {
parents.add(parent); // store the last parent
}
else {
throw new IllegalArgumentException("Invaid file data: " + line);
}
}
}
class Parent {
private String data;
private List<Child> children = new ArrayList<>();
public Parent(String s) {
data = s;
}
public void addChild(Child c) {
children.add(c);
}
public String toString() {
return data + ": " + children.toString();
}
}
class Child {
private String name;
private String dataA;
private String dataB;
public Child(String s, String a, String b) {
name = s;
dataA = a;
dataB = b;
}
public String toString() {
return name + ": " + dataA + ", " + dataB;
}
}
示例输入文件-complex_data.txt:
START
PARENT1 dataX dataY
CHILD1 dataA dataB
CHILD2 dataC DataD
PARENT2 dataJ dataK
CHILD1 dataE dataF
PARENT3 dataZ dataZ
END
输出:
[PARENT1 dataX dataY: [CHILD1: dataA, dataB, CHILD2: dataC, DataD], PARENT2 dataJ dataK: [CHILD1: dataE, dataF], PARENT3 dataZ dataZ: []]