title: Get last element of Stream/List in a one-liner
body: <p>How can I get the last element of a stream or list in the following code?</p>
  
  <p>Where <code>data.careas</code> is a <code>List&lt;CArea&gt;</code>:</p>
  
  <pre><code>CArea first = data.careas.stream()
                    .filter(c -&gt; c.bbox.orientationHorizontal).findFirst().get();
  
  CArea last = data.careas.stream()
                   .filter(c -&gt; c.bbox.orientationHorizontal)
                   .collect(Collectors.toList()).; //how to?
  </code></pre>
  
  <p>As you can see getting the first element, with a certain <code>filter</code>, is not hard.</p>
  
  <p>However getting the last element in a one-liner is a real pain:</p>
  
  <ul>
  <li>It seems I cannot obtain it directly from a <code>Stream</code>. (It would only make sense for finite streams)</li>
  <li>It also seems that you cannot get things like <code>first()</code> and <code>last()</code> from the <code>List</code> interface, which is really a pain.</li>
  </ul>
  
  <p>I do not see any argument for not providing a <code>first()</code> and <code>last()</code> method in the <code>List</code> interface, as the elements in there, are ordered, and moreover the size is known.</p>
  
  <p>But as per the original answer: How to get the last element of a finite <code>Stream</code>?</p>
  
  <p>Personally, this is the closest I could get:</p>
  
  <pre><code>int lastIndex = data.careas.stream()
          .filter(c -&gt; c.bbox.orientationHorizontal)
          .mapToInt(c -&gt; data.careas.indexOf(c)).max().getAsInt();
  CArea last = data.careas.get(lastIndex);
  </code></pre>
  
  <p>However it does involve, using an <code>indexOf</code> on every element, which is most likely not you generally want as it can impair performance.</p>