Suppose I have a non-binary tree structure (each node may have n
child nodes). In that sense, what could be a good method for flattening the whole tree into a single list using java streams?
rootNode.getChildren().stream()
.flatMap(node -> node.getChildren().stream())
.collect(Collectors.toList());
This example is what I would do for a single level flattening, and still such would not include the root node (which is desired).
Lets call your class Node
. In that class, add the method (assuming getChildren()
never return null
) :
public Stream<Node> streamAll(){
return Stream.concat(Stream.of(this), getChildren().stream().flatMap(Node::streamAll));
}
Then to get a list, you can simply call
rootNode.streamAll().collect(Collectors.toList());
or since java 16
rootNode.streamAll().toList();