title: How to recursively flatMap a stream?
body: <p>I was asked to retrieve every leaf node that is a descandant of a tree node. I quickly got the idea that I could do this job in one line!</p>
  
  <pre><code>public Set&lt;TreeNode&lt;E&gt;&gt; getLeaves() {
      return getChildrenStream().flatMap(n -&gt; n.getChildrenStream()).collect(toSet());
  }
  </code></pre>
  
  <p>It was good at the first glance, but quickly it ran into a <code>StackOverflowExcepetion</code>if the tree depth reaches ~10, something that I can't accept. Later I developed a implementation without recursion and stream (but with my brain <em>roasted</em>), but I'm still wondering if there is a way to do recursive <code>flatMap</code>s with stream, because I found it impossible to do so without touching the stream internals. It'll need a new Op, like <code>RecursiveOps</code> to do that, or I will have to collect all results into a <code>Set</code> every step, and operate on that <code>Set</code> later:</p>
  
  <pre><code>Set&lt;TreeNode&lt;E&gt;&gt; prev = new HashSet&lt;&gt;();
  prev.add(this);
  while (!prev.isEmpty()) {
      prev = prev.stream().flatMap(n -&gt; n.getChildrenStream()).collect(toSet());
  }
  return prev;
  </code></pre>
  
  <p>Not good as it seems to be. Streams are meant to be a pipeline. Its result and intermediate results are not computed until a terminal op is added. The above approach appearently violates that principle. It's not as easy to parellelize as streams, too. Can I recursively flatMap without manually computing all intermediate results?</p>
  
  <p>PS1: the TreeNode declaration:</p>
  
  <pre><code>public class TreeNode&lt;E&gt; {
      // ...
      /**
       * Get a stream of children of the current node. 
       *
       */
      public Stream&lt;TreeNode&lt;E&gt;&gt; getChildrenStream(){
          // ...
      }
  
      public Set&lt;TreeNode&lt;E&gt;&gt; getLeaves() {
          // main concern
      }
  }f
  </code></pre>