Simplest way to get the top n elements of a Scala Iterable

前端 未结 9 669
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 02:48

Is there a simple and efficient solution to determine the top n elements of a Scala Iterable? I mean something like

iter.toList.sortBy(_.myAttr).take(2)
         


        
9条回答
  •  死守一世寂寞
    2020-11-29 03:27

    Yet another version:

    val big = (1 to 100000)
    
    def maxes[A](n:Int)(l:Traversable[A])(implicit o:Ordering[A]) =
        l.foldLeft(collection.immutable.SortedSet.empty[A]) { (xs,y) =>
          if (xs.size < n) xs + y
          else {
            import o._
            val first = xs.firstKey
            if (first < y) xs - first + y
            else xs
          }
        }
    
    println(maxes(4)(big))
    println(maxes(2)(List("a","ab","c","z")))
    

    Using the Set force the list to have unique values:

    def maxes2[A](n:Int)(l:Traversable[A])(implicit o:Ordering[A]) =
        l.foldLeft(List.empty[A]) { (xs,y) =>
          import o._
          if (xs.size < n) (y::xs).sort(lt _)
          else {
            val first = xs.head
            if (first < y) (y::(xs - first)).sort(lt _)
            else xs
          }
        }
    

提交回复
热议问题