gpt4 book ai didi

tree - 是否可以使用 Java 8 Streams 构建 Tree 数据模型

转载 作者:行者123 更新时间:2023-12-01 02:40:19 26 4
gpt4 key购买 nike

我正在研究 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

我得到的最接近的 key 重复失败

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<>();

}

直接从我的输入文件流中构造所有树节点和完全填充的子节点列表。

最佳答案

这是 groupingBy 收集器的工作:

import static java.util.stream.Collectors.*;

Pattern ptrn = Pattern.compile("Parent (.*) - Child (.*)");

Map<String, List<String>> map = data.stream()
.sorted()
.map(ptrn::matcher)
.filter(Matcher::find)
.collect(groupingBy(
m -> m.group(1),
LinkedHashMap::new ,
mapping(m -> m.group(2), toList())
));

关于tree - 是否可以使用 Java 8 Streams 构建 Tree 数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40294780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com