I would like to write a Java 8 stream().collect
function that return a List<T>
containing all children and subchildren of a node within a hierarchical structure. For example TreeItem<T>
getChildren()
and all of the children's children and so on, reducing it to a single list.
By the way, here is my final solution as generic method. Very effective and very useful.
public static <T> Stream<T> treeStream(T root, boolean includeRoot, Function<T, Stream<? extends T>> nextChildren)
{
Stream<T> stream = nextChildren.apply(root).flatMap(child -> treeStream(child, true, nextChildren));
return includeRoot ? Stream.concat(Stream.ofNullable(root), stream) : stream;
}