title: Java 8: stop reduction operation from examining all Stream elements
body: <p>I am trying to understand if there is a way to terminate reduction operation without examining the whole stream and I cannot figure out a way.</p>
  
  <p>The use-case is roughly as follows: let there be a long list of <code>Integer</code>s which needs to be folded into an <code>Accumulator</code>. Each element examination is potentially expensive, so within the <code>Accumulator</code>, I perform a check on the incoming <code>Accumulator</code> to see if we even need to perform expensive operation - if we don't, then I simply return the accumulator.</p>
  
  <p>This is obviously a fine solution for small(er) lists but huge lists incur unnecessary stream element visiting costs I'd like to avoid.</p>
  
  <p>Here's a code sketch - assume serial reductions only.</p>
  
  <pre><code>class Accumulator {
      private final Set&lt;A&gt; setA = new HashSet&lt;&gt;;
      private final Set&lt;B&gt; setB = new HashSet&lt;&gt;;
  }
  
  class ResultSupplier implements Supplier&lt;Result&gt; {
  
      private final List&lt;Integer&gt; ids;
  
      @Override
      public Result get() {
          Accumulator acc = ids.stream().reduce(new Accumulator(), f(), (x, y) -&gt; null);
  
          return (acc.setA.size &gt; 1) ? Result.invalid() : Result.valid(acc.setB);
      }
  
      private static BiFunction&lt;Accumulator, Integer, Accumulator&gt; f() {
          return (acc, element) -&gt; {
              if (acc.setA.size() &lt;= 1) {
                  // perform expensive ops and accumulate results
              }
              return acc;
          };
      }
  }
  </code></pre>
  
  <p>In addition to having to traverse the whole <code>Stream</code>, there is another fact I dislike - I have to check the same condition <em>twice</em> (namely, <code>setA</code> size check).</p>
  
  <p>I have considered <code>map()</code> and <code>collect()</code> operations but they just seemed like more of the same and didn't find they materially change the fact that I just can't finish the fold operation without examining the entire stream.</p>
  
  <p>Additionally, my thinking is that imaginary <code>takeWhile(p : (A) =&gt; boolean)</code> Stream API correspondent would also buy us nothing, as the terminating condition depends on the accumulator, not stream elements per se.</p>
  
  <p>Bear in mind I am a relative newcomer to FP so - is there a way to make this work as I expect it? Have I set up the whole problem improperly or is this limitation by design?</p>