I want to convert a tree in a Java8 stream of nodes.
Here is a tree of nodes storing data which can be selected:
public class SelectTree {
I find this implementation of stream() which is a DFS tree traversal:
public class SelectTree {
//...
public Stream> 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));
}
}
}
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 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)) ;
}
}