title: Computing all values or stopping and returning just the best value if found
body: <p>I have a list of items and for each item I am computing a value. Computing this value is a bit computationally intensive so I want to minimise it as much as possible.</p>
  
  <p>The algorithm I need to implement is this:</p>
  
  <ol>
  <li><p>I have a value X</p></li>
  <li><p>For each item</p>
  
  <p>a. compute the value for it, if it is &lt; 0 ignore it completely</p>
  
  <p>b. if (value > 0) &amp;&amp; (value &lt; X)
        return pair (item, value) </p></li>
  <li><p>Return all (item, value) pairs in a List (that have the value > 0), ideally sorted by value</p></li>
  </ol>
  
  <p>To make it a bit clearer, step 3 only happens if none of the items have a value less than X. In step 2, when we encounter the first item that is less than X we should not compute the rest and just return that item (we can obviously return it in a Set() by itself to match the return type).</p>
  
  <p>The code I have at the moment is as follows:</p>
  
  <pre><code>  val itemValMap = items.foldLeft(Map[Item, Int)]()) {
    (map : Map[Item, Int], key : Item) =&gt;
      val value = computeValue(item)
      if ( value &gt;= 0 )        //we filter out negative ones
        map + (key -&gt; value)
      else
        map
    }
  
   val bestItem = itemValMap.minBy(_._2)
   if (bestItem._2 &lt; bestX)
   {
        List(bestItem)
   }
   else
   {
      itemValMap.toList.sortBy(_._2)
   }
  </code></pre>
  
  <p>However, what this code is doing is computing all the values in the list and choosing the best one, rather than stopping as a 'better' one is found. I suspect I have to use Streams in some way to achieve this?</p>