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 {
A more general approach using any node class is to add a parameter for the method, which returns the children:
public class TreeNodeStream {
public static Stream of(T node, Function> childrenFunction) {
return Stream.concat( //
Stream.of(node), //
childrenFunction.apply(node).stream().flatMap(n -> of(n, childrenFunction)));
}
}
An example using File:
TreeNodeStream.of(
new File("."), f -> f.isDirectory() ? Arrays.asList(f.listFiles()) :
Collections.emptySet())
.filter(f -> f.getName().endsWith(".java"))
.collect(Collectors::toList);