How to convert a tree structure to a Stream of nodes in java

后端 未结 3 1067
甜味超标
甜味超标 2020-12-16 02:42

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 {

           


        
3条回答
  •  天命终不由人
    2020-12-16 03:21

    One small addition to kwisatz's answer.

    This implementation:

    this.getChildren().stream()
            .map(SelectTree::stream)
            .reduce(Stream.of(this), Stream::concat);
    

    will be more eager, i. e. the whole hierarchy will be traversed during a stream creation. If your hirarchy is large and, let's say, you're looking for a single node matching some predicate, you may want a more lazy behaviour:

    Stream.concat(Stream.of(this),
                  this.getChildren().stream().flatMap(SelectTree::stream));
    

    In this case, only the children of the root node will be retrieved during a stream creation, and a search for a node won't necessarily result in the whole hierarchy being traversed.

    Both approaches will exhibit the DFS iteration order.

提交回复
热议问题