title: How to reuse application of filter & map on a Stream?
body: <p>I have a set of domain objects that inherit from a shared type (i.e. <code>GroupRecord extends Record</code>, <code>RequestRecord extends Record</code>). The subtypes have specific properties (i.e. <code>GroupRecord::getCumulativeTime</code>, <code>RequestRecord::getResponseTime</code>).</p>
  
  <p>Further, I have a list of records with mixed subtypes as a result of parsing a logfile.</p>
  
  <pre><code>List&lt;Record&gt; records = parseLog(...);
  </code></pre>
  
  <p>In order to compute statistics on the log records, I want to apply math functions only on a subset of the records that matches a specific subtype, i.e. only on <code>GroupRecord</code>s. Therefore I want to have a filtered stream of specific subtypes. I know that I can apply a <code>filter</code> and <code>map</code> to a subtype using</p>
  
  <pre><code>records.stream()
         .filter(GroupRecord.class::isInstance)
         .map(GroupRecord.class::cast)
         .collect(...
  </code></pre>
  
  <p>Apply this filter&amp;cast on the stream multiple times (especially when doing it for the same subtype multiple times for different computations) is not only cumbersome but produces lots of duplication. </p>
  
  <p>My current approach is to use a <code>TypeFilter</code> </p>
  
  <pre><code>class TypeFilter&lt;T&gt;{
  
      private final Class&lt;T&gt; type;
  
      public TypeFilter(final Class&lt;T&gt; type) {
          this.type = type;
      }
  
      public Stream&lt;T&gt; filter(Stream&lt;?&gt; inStream) {
          return inStream.filter(type::isInstance).map(type::cast);
      }
  }
  </code></pre>
  
  <p>To be applied to a stream:</p>
  
  <pre><code>TypeFilter&lt;GroupRecord&gt; groupFilter = new TypeFilter(GroupRecord.class); 
  
  SomeStatsResult stats1 = groupFilter.filter(records.stream())
                                        .collect(...)
  SomeStatsResult stats2 = groupFilter.filter(records.stream())
                                        .collect(...)
  </code></pre>
  
  <p>It works, but I find this approach a bit much for such a simple task. Therefore I wonder, is there a better or what is the best way for making this behavior reusable using streams and functions in a concise and readable way?</p>