What's the best way to inverse sort in scala?

前端 未结 9 1838
感情败类
感情败类 2020-12-12 10:11

What is the best way to do an inverse sort in scala? I imagine the following is somewhat slow.

list.sortBy(_.size).reverse

Is there a conv

9条回答
  •  余生分开走
    2020-12-12 10:39

    sortBy has implicit parameter ord which provides ordering

    def sortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A]
    

    so, we can define own Ordering object

    scala> implicit object Comp extends Ordering[Int] {
     | override def compare (x: Int, y: Int): Int = y - x
     | }
    defined module Comp
    
    List(3,2,5,1,6).sortBy(x => x)
    res5: List[Int] = List(6, 5, 3, 2, 1)
    

提交回复
热议问题