更新时间:2021-11-29 16:49:44
您可以为每个以其名称索引的Row
创建一个Map
:
You could create a Map
of each Row
indexed by it's name:
Map<String,Row> nodes = list.stream().collect(Collectors.toMap(Row::getName,Function.identity()));
getName()
是传递给Row
构造函数的第二个属性.
getName()
being the second property passed to the Row
constructor.
现在,您可以使用该Map
来构建树:
Now you can use that Map
to build the tree:
Map<Row,List<Row>> tree = list.stream().collect(Collectors.groupingBy(r->nodes.get(r.getParent())));
getParent()
是传递给Row
构造函数的第一个属性.
getParent()
being the first property passed to the Row
constructor.
这将要求Row
类正确覆盖equals
和hashCode
,以便两个具有相同名称的Row
实例被视为相等.
This would require the Row
class to override equals
and hashCode
properly, so that two Row
instances will be considered equal if they have the same name.
您可能应该将根Row
添加到输入List
中.像这样:
You should probably add a root Row
to your input List
though. Something like:
list.add(new Row(null, "-", "Root"));
我使用完整的Row
类对其进行了测试(尽管我做了一些捷径),其中包括一个从树根遍历每个级别的第一个孩子的示例:
I tested it with a full Row
class (though I made some shortcuts), including an example of traversing the tree from the root along the first child of each level:
class Row {
String name;
String parent;
Row (String parent,String name,String something) {
this.parent = parent;
this.name = name;
}
public String getParent () {return parent;}
public String getName () {return name;}
public int hashCode () {return name.hashCode ();}
public boolean equals (Object other) {
return ((Row) other).name.equals (name);
}
public String toString ()
{
return name;
}
public static void main (String[] args)
{
List<Row> list = new ArrayList<>();
list.add(new Row(null, "-", "Root"));
list.add(new Row("-", "A", "Root"));
list.add(new Row("A", "A1", "Alpha 1"));
list.add(new Row("A1", "A11", "Alpha 11"));
list.add(new Row("A", "A2", "Alpha 2"));
list.add(new Row("-", "B", "Root"));
list.add(new Row("B", "B1", "Bravo 1"));
list.add(new Row("B", "B2", "Bravo 2"));
Map<String,Row> nodes =
list.stream()
.collect(Collectors.toMap(Row::getName,Function.identity()));
Map<Row,List<Row>> tree =
list.stream()
.filter(r->r.getParent()!= null)
.collect(Collectors.groupingBy(r->nodes.get(r.getParent())));
System.out.println (tree);
Row root = nodes.get ("-");
while (root != null) {
System.out.print (root + " -> ");
List<Row> children = tree.get (root);
if (children != null && !children.isEmpty ()) {
root = children.get (0);
} else {
root = null;
}
}
System.out.println ();
}
}
输出:
树:
{A1=[A11], A=[A1, A2], B=[B1, B2], -=[A, B]}
遍历:
- -> A -> A1 -> A11 ->