我正在研究Java 8流。
目前,我正试图通过流式处理文件来构建经典的树形结构,其中每个记录描述了父子关系。
我希望我的解决方案能够从类似以下示例的输入数据记录中构建树:
Parent A - Child B
Parent A - Child C
Parent A - Child D
Parent A - Child E
Parent B - Child F
Parent B - Child G
Parent C - Child H
Parent D - Child I
Parent G - Child J
我想要构建一个
LinkedHashMap<String, List<String>>
,例如最终结果为:A - B, C, D, E
B - F, G
C - H
D - I
G - J
我最接近的尝试失败了,出现了重复的键。
Map<String, List<String>> map = stream.sorted().map(line -> line.split("-")).flatMap(line -> Arrays.stream(line)).collect(Collectors.toMap(Function.identity(), Arrays::asList));
或者使用以下的
Node
值对象。public class Node {
private final String name;
private Node parent;
private List<Node> children = new LinkedList<>();
}
从我的输入文件中直接构建所有树节点,同时填充完整的子节点列表。