Sam*_*Sam 3 java tree java-8 java-stream
如果我的层次结构仍处于排序状态,但已展平 - 如何使用 Java Streams API 创建父/子结构?一个例子:我如何从
-,A,Foo
A,A1,Alpha1
A,A2,Alpha2
-,B,Bar
B,B1,Bravo1
B,B2,Bravo2
Run Code Online (Sandbox Code Playgroud)
到
-
A
A1,Alpha1
A2,Alpha2
B
B1,Bravo1
B2,Bravo2
Run Code Online (Sandbox Code Playgroud)
一种简单的非流方式是跟踪父列并查看它是否已更改。
我已经尝试过使用 Collectors 和 groupingBy 的各种方法,但还没有找到方法。
List<Row> list = new ArrayList<>();
list.add(new Row("-", "A", "Root"));
list.add(new Row("A", "A1", "Alpha 1"));
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"));
//Edit
Map<Row, List<Row>> tree;
tree = list.stream().collect(Collectors.groupingBy(???))
Run Code Online (Sandbox Code Playgroud)
您可以创建一个按名称索引Map
的每个Row
索引:
Map<String,Row> nodes = list.stream().collect(Collectors.toMap(Row::getName,Function.identity()));
Run Code Online (Sandbox Code Playgroud)
getName()
作为传递给Row
构造函数的第二个属性。
现在您可以使用它Map
来构建树:
Map<Row,List<Row>> tree = list.stream().collect(Collectors.groupingBy(r->nodes.get(r.getParent())));
Run Code Online (Sandbox Code Playgroud)
getParent()
是传递给Row
构造函数的第一个属性。
这将要求Row
类正确地覆盖equals
和hashCode
正确,以便两个Row
实例如果具有相同的名称,则将被认为是相等的。
不过,您可能应该Row
在输入中添加一个根List
。就像是:
list.add(new Row(null, "-", "Root"));
Run Code Online (Sandbox Code Playgroud)
编辑:
我用一个完整的Row
类对其进行了测试(尽管我做了一些快捷方式),包括一个从根沿着每个级别的第一个子节点遍历树的示例:
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 ();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
那个树:
{A1=[A11], A=[A1, A2], B=[B1, B2], -=[A, B]}
Run Code Online (Sandbox Code Playgroud)
遍历:
- -> A -> A1 -> A11 ->
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
732 次 |
最近记录: |