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

后端 未结 3 1069
甜味超标
甜味超标 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:24

    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)) ;
        }
      }
    

提交回复
热议问题