【发布时间】:2020-07-28 09:30:05
【问题描述】:
所以我有一个 Map
David -> [Claire]
Claire -> [Matt]
Matt -> [Sean, Terry]
我知道上面例子中树的根应该是大卫,它只有一个根。
示例输出
{
"David": {
"Claire": {
"Matt": {
"Sean": {},
"Terry": {}
}
}
}
}
我尝试了几件事,但真的很难过。
编辑:到目前为止尝试的代码
public Set<Tree> transform(Map<String, ArrayList<String>> input) {
Set<String> roots = new HashSet<String>(input.keySet());
Map<String, Tree> map = new HashMap<String, Tree>();
for (Map.Entry<String, ArrayList<String>> entry : input.entrySet()) {
String key = entry.getKey();
List<String> childKeys = entry.getValue();
Tree tree = map.get(key);
if (tree == null) {
tree = new Tree(key);
map.put(key, tree);
}
for (String childKey : childKeys) {
roots.remove(childKey);
Tree child = map.get(childKey);
if (child == null) {
child = new Tree(childKey);
map.put(childKey, child);
}
tree.addChild(child);
}
}
Set<Tree> res = new HashSet<Tree>(roots.size());
for (String key : roots) {
res.add(map.get(key));
}
return res;
}
树类:
public class Tree {
private String key;
private Tree child;
public Tree(String key){
this.key = key;
}
public void addChild(Tree child){
this.child = child;
}
}
问题是当我使用此代码时,我得到的输出(调试/打印后的集合中的内容)是
David:
Claire:
Matt:
Terry:
【问题讨论】:
-
"我尝试了一些东西" 你能展示一下你尝试了什么吗?您是在尝试手动生成 JSON,还是您有需要帮助的特定库?
-
在生成 JSON 时,我们试图以一种通用的方式来实现它,例如获取根并为它下面的每个孩子创建一个 json 对象。所以会遍历每一个。我会尝试重现一些已经完成的事情(删除和 ctrl-z'd 的东西非常沮丧)关于库或从字符串中制作它真的没有偏好。
-
如果地图上的第一个条目是
David -> [Claire, Matt]怎么办?你对Matt编码两次吗? -
对不起,我忘记了,现在将添加它。只有一个孩子可以有一个父母。所以大卫不可能是马特的父母,而克莱尔不可能是马特的父母。
-
我可以在这里看到两件事:1 将初始结构转换为树 2 序列化。如果结构正确,第二个应该是微不足道的。