title: Simplest way to get the top n elements of a Scala Iterable
body: <p>Is there a simple and efficient solution to determine the top n elements of a Scala Iterable? I mean something like</p>
  
  <pre><code>iter.toList.sortBy(_.myAttr).take(2)
  </code></pre>
  
  <p>but without having to sort all elements when only the top 2 are of interest.  Ideally I'm looking for something like</p>
  
  <pre><code>iter.top(2, _.myAttr)
  </code></pre>
  
  <p>see also: Solution for the top element using an Ordering: <a href="https://stackoverflow.com/questions/2190511">In Scala, how to use Ordering[T] with List.min or List.max and keep code readable</a></p>
  
  <h2>Update:</h2>
  
  <p>Thank you all for your solutions.  Finally, I took the original solution of <em>user unknown</em> and adopted it to use <code>Iterable</code> and the <em>pimp-my-library</em> pattern:</p>
  
  <pre><code>implicit def iterExt[A](iter: Iterable[A]) = new {
    def top[B](n: Int, f: A =&gt; B)(implicit ord: Ordering[B]): List[A] = {
      def updateSofar (sofar: List [A], el: A): List [A] = {
        //println (el + " - " + sofar)
  
        if (ord.compare(f(el), f(sofar.head)) &gt; 0)
          (el :: sofar.tail).sortBy (f)
        else sofar
      }
  
      val (sofar, rest) = iter.splitAt(n)
      (sofar.toList.sortBy (f) /: rest) (updateSofar (_, _)).reverse
    }
  }
  
  case class A(s: String, i: Int)
  val li = List (4, 3, 6, 7, 1, 2, 9, 5).map(i =&gt; A(i.toString(), i))
  println(li.top(3, _.i))
  </code></pre>