title: Java 8 Streams: count all elements which enter the terminal operation
body: <p>I wonder whether there is a nicer (or just an other) approach to get the count of all items that enter the terminal operation of a stream instead of the following:</p>
  
  <pre><code>Stream&lt;T&gt; stream = ... // given as parameter
  AtomicLong count = new AtomicLong();
  stream.filter(...).map(...)
        .peek(t -&gt; count.incrementAndGet())
  </code></pre>
  
  <p>where <code>count.get()</code> gives me the actual count of the processed items at that stage.</p>
  
  <p>I deliberately skipped the terminal operation as that might change between <code>.forEach</code>, <code>.reduce</code> or <code>.collect</code>.
  I do know <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#count--" rel="noreferrer"><code>.count</code></a> already, but it seems to work well only if I exchange a <code>.forEach</code> with a <code>.map</code> and use the <code>.count</code> as terminal operation instead. But it seems to me as if <code>.map</code> is then misused.</p>
  
  <p>What I don't really like with the above solution: if a filter is added after it, it just counts the elements at that specific stage, but not the ones that are going into the terminal operation.</p>
  
  <p>The other approach that comes to my mind is to <code>collect</code> the filtered and mapped values into a list and operate on that and just call <code>list.size()</code> to get the count. However this will not work, if the collection of the stream would lead to an error, whereas with the above solution I could have a count for all processed items so far, if an appropriate <code>try/catch</code> is in place. That however isn't a hard requirement.</p>