更新时间:2023-02-05 20:14:05
我发现 stream()
的这个实现是一个 DFS 树遍历:
I find this implementation of stream()
which is a DFS tree traversal:
public class SelectTree<D> {
//...
public Stream<SelectTree<D>> stream() {
if (this.isLeaf()) {
return Stream.of(this);
} else {
return this.getChildren().stream()
.map(child -> child.stream())
.reduce(Stream.of(this), (s1, s2) -> Stream.concat(s1, s2));
}
}
}
如果你不能像 primefaces TreeNode
(org.primefaces.model.TreeNode
) 那样更改树的实现,你可以在其他类中定义一个方法:
If you can't change the tree implementation like for primefaces TreeNode
(org.primefaces.model.TreeNode
) you can define a method in an other class:
public Stream<TreeNode> stream(TreeNode parentNode) {
if(parentNode.isLeaf()) {
return Stream.of(parentNode);
} else {
return parentNode.getChildren().stream()
.map(childNode -> stream(childNode))
.reduce(Stream.of(parentNode), (s1, s2) -> Stream.concat(s1, s2)) ;
}
}