title: Java Stream: find an element with a min/max value of an attribute
body: <p>I have a stream of objects and I would like to find the one with a maximal value of some attribute that's expensive to calculate.</p>
  
  <p>As a specific simple example, say that we have a list of strings and we want to find the coolest one, given a <code>coolnessIndex</code> function.</p>
  
  <p>The following should work:</p>
  
  <pre><code>String coolestString = stringList
          .stream()
          .max((s1, s2) -&gt; Integer.compare(coolnessIndex(s1), coolnessIndex(s2)))
          .orElse(null);
  </code></pre>
  
  <p>Now, there are two problems with this. First, assuming the <code>coolnessIndex</code> is expensive to calculate, this probably won't be very efficient. I suppose the <code>max</code> method will need to use the comparator repeatedly, which in turn will call the <code>coolnessIndex</code> repeatedly and at the end it will be called more than once for each string.</p>
  
  <p>Second, having to provide the comparator leads to some redundancy in the code. I would much prefer syntax like this:</p>
  
  <pre><code>String coolestString = stringList
          .stream()
          .maxByAttribute(s -&gt; coolnessIndex(s))
          .orElse(null);
  </code></pre>
  
  <p>However, I haven't been able to find a matching method in the <code>Stream</code> API. This surprises me, since finding min/max by an attribute seems like a common pattern. I wonder if there's a better way than using the comparator (other than a for loop).</p>