title: Java Streams: How to do an efficient "distinct and sort"?
body: <p>Let's assume I've got a <code>Stream&lt;T&gt;</code> and want to get only distinct elements and sorted.</p>
  
  <p>The naïve approach would be to do just the following:</p>
  
  <pre><code>Stream.of(...)
      .sorted()
      .distinct()
  </code></pre>
  
  <p>or, maybe the other way around:</p>
  
  <pre><code>Stream.of(...)
      .distinct()
      .sorted()
  </code></pre>
  
  <p>Since the implementation of both of them is not really accessible by the JDK's source code I was just wondering about possible memory consumption and performance implications.</p>
  
  <p>Or would it be even more efficient to write my own filter as the following?</p>
  
  <pre><code>Stream.of(...)
      .sorted()
      .filter(noAdjacentDuplicatesFilter())
  
  public static Predicate&lt;Object&gt; noAdjacentDuplicatesFilter() {
      final Object[] previousValue = {new Object()};
  
      return value -&gt; {
          final boolean takeValue = !Objects.equals(previousValue[0], value);
          previousValue[0] = value;
          return takeValue;
      };
  }
  </code></pre>