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

前端 未结 9 1795
感情败类
感情败类 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:43

    maybe to shorten it a little more:

    def Desc[T : Ordering] = implicitly[Ordering[T]].reverse
    
    List("1","22","4444","333").sortBy( _.size )(Desc)
    
    0 讨论(0)
  • 2020-12-12 10:55

    Both sortWith and sortBy have a compact syntax:

    case class Foo(time:Long, str:String)
    
    val l = List(Foo(1, "hi"), Foo(2, "a"), Foo(3, "X"))
    
    l.sortWith(_.time > _.time)  // List(Foo(3,X), Foo(2,a), Foo(1,hi))
    
    l.sortBy(- _.time)           // List(Foo(3,X), Foo(2,a), Foo(1,hi))
    
    l.sortBy(_.time)             // List(Foo(1,hi), Foo(2,a), Foo(3,X))
    

    I find the one with sortWith easier to understand.

    0 讨论(0)
  • 2020-12-12 10:56

    There may be the obvious way of changing the sign, if you sort by some numeric value

    list.sortBy(- _.size)
    

    More generally, sorting may be done by method sorted with an implicit Ordering, which you may make explicit, and Ordering has a reverse (not the list reverse below) You can do

    list.sorted(theOrdering.reverse)
    

    If the ordering you want to reverse is the implicit ordering, you can get it by implicitly[Ordering[A]] (A the type you're ordering on) or better Ordering[A]. That would be

    list.sorted(Ordering[TheType].reverse)
    

    sortBy is like using Ordering.by, so you can do

    list.sorted(Ordering.by(_.size).reverse)
    

    Maybe not the shortest to write (compared to minus) but intent is clear

    Update

    The last line does not work. To accept the _ in Ordering.by(_.size), the compiler needs to know on which type we are ordering, so that it may type the _. It may seems that would be the type of the element of the list, but this is not so, as the signature of sorted is def sorted[B >: A](ordering: Ordering[B]). The ordering may be on A, but also on any ancestor of A (you might use byHashCode : Ordering[Any] = Ordering.by(_.hashCode)). And indeed, the fact that list is covariant forces this signature. One can do

    list.sorted(Ordering.by((_: TheType).size).reverse)
    

    but this is much less pleasant.

    0 讨论(0)
提交回复
热议问题