title: Using Java Streams for Efficient Search
body: <p>I have a <code>List</code> of elements that have no measurable order among them. Their attributes are also complex enough that I cannot simply insert them into a <code>Set</code> (since different attributes may represent the same element). </p>
  
  <p>Through the course of my program, I analyse each element in the list and, based on it, other elements are added (like building a graph and going to each node to add additional paths and nodes). However, they added elements may be equivalent to other elements in the <code>List</code>. In this case they are not added, and the equivalent element has a property changed (let's assume, a counter). </p>
  
  <p>I've been using this code to find whether an equivalent state exists:</p>
  
  <pre><code>public static State stateAlreadyExists(State current) {
      for (State any : list) {
          if (equivalencyMethod(any, current)) {
              return any;
          }
       }
       return null;
  }
  </code></pre>
  
  <p>However, this code, albeit having <code>O(n)</code> complexity, is not performant enough for my case. Every element I add will have this code executed, and I add about <code>sqrt(N)</code> elements per analysed element (so, analysing the element 400 is creating 20 new elements, for example). To increase the performance, I used Java's parallel streams:</p>
  
  <pre><code>public static State stateAlreadyExists(State current) {
      Optional&lt;State&gt; opt = list.parallelStream().filter(
          any -&gt; equivalencyMethod(any, current)).findFirst();
      if (opt.isPresent()) {
          return opt.get();
      }
      return null;
  }
  </code></pre>
  
  <p>And the performance increased significantly. <strike>The problem is this code isn't really equivalent, since we analyse the entire stream before returning an element. Most times, the equivalent element is in the first <code>sqrt(N)</code> elements of the list, so a method that stops on the first match would be better.</p>
  
  <p>I'm aware there is a <code>noneFound()</code> method for <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" rel="nofollow">streams</a>. It returns as soon as a match is found. However, it returns a <code>boolean</code>, not the element itself. Is there a way to use this or a similarly built method to return the first match found?</strike></p>
  
  <p>According to the JavaDoc, findFirst():</p>
  
  <blockquote>
    <p>returns the first element of this stream</p>
  </blockquote>
  
  <p>While findAny():</p>
  
  <blockquote>
    <p>selects any element in the stream. This is to allow for maximal performance in parallel operations.</p>
  </blockquote>
  
  <p>So, my code can become even more performant by using the <code>findAny()</code> call, since order doesn't really matter for my problem, due to there being only 1 equivalent element at any time.</p>