title: Transform Java Stream and return reduced values both
body: <p>Assuming I consume a Stream of entities from a source which I do not want to materialize, and I want to both transform the elements, and return some globally reduced value, what is the idiomatic way with java(8)?</p>
  
  <p>This is essentially trying to perform both a <code>reduce()</code> and a <code>collect()</code>.</p>
  
  <p>Example:</p>
  
  <pre class="lang-java prettyprint-override"><code>class Person {
      public String firstname,
      public String lastname,
      public int age;
  }
  
  class TeamSummary {
      public List&lt;String&gt; fullnames, // firstname and lastname of all
      public Person oldest
  }
  
  public TeamSummary getSummary(Stream&lt;Person&gt; personStream) {
     final TeamSummary summary = new Summary();
     summary.fullnames = personStream
         .peek(p -&gt; if (summary.getOldest() == null || summary.getOldest.age &lt; p.age) {
             summary.oldest = p;
         })
         .map(p -&gt; p.firstname + ' ' + p.lastname)
         .collect(toList());
     return summary;
  }
  </code></pre>
  
  <p>It looks ugly to interact with a variable outside the stream inside the peek method, but what good alternatives are there, it seems I need to combine <code>collect()</code> and <code>reduce()</code>.</p>
  
  <p>It get's worse if I want to get a reduced value from the whole stream (like average age), and a filtered list (like Persons above 18 years). It also get's worse if TeamSummary is an immutable class, and additional mutable variables are required.</p>
  
  <p>In such cases it is more idiomatic to use a while loop on stream.iterator() to avoid coupling of stream methods and variables? Or is it natural to use reduce to a tuple like (oldest, accumulated).</p>
  
  <p>I am aware this question is a matter of opinion unless there is an obvious way (like a special collector) that solves this elegantly.</p>