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

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

    Another possibility in cases where you pass a function that you may not be able to modify directly to an Arraybuffer via sortWith for example:

    val buf = collection.mutable.ArrayBuffer[Int]()
    buf += 3
    buf += 9
    buf += 1
    
    // the sort function (may be passed through from elsewhere)
    def sortFn = (A:Int, B:Int) => { A < B }
    
    // the two ways to sort below
    buf.sortWith(sortFn)                        // 1, 3, 9
    buf.sortWith((A,B) => { ! sortFn(A,B) })    // 9, 3, 1
    
    0 讨论(0)
  • 2020-12-12 10:31
    list.sortBy(_.size)(Ordering[Int].reverse)
    
    0 讨论(0)
  • 2020-12-12 10:35

    Easy peasy (at least in case of size):

    scala> val list = List("abc","a","abcde")
    list: List[java.lang.String] = List(abc, a, abcde)
    
    scala> list.sortBy(-_.size)
    res0: List[java.lang.String] = List(abcde, abc, a)
    
    scala> list.sortBy(_.size)
    res1: List[java.lang.String] = List(a, abc, abcde)
    
    0 讨论(0)
  • 2020-12-12 10:36
    val list = List(2, 5, 3, 1)
    list.sortWith(_>_) -> res14: List[Int] = List(5, 3, 2, 1)
    list.sortWith(_<_) -> res14: List[Int] = List(1, 2, 3, 5)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-12 10:42

    this is my code ;)

    val wordCounts = logData.flatMap(line => line.split(" "))
                            .map(word => (word, 1))
                            .reduceByKey((a, b) => a + b)
    
    wordCounts.sortBy(- _._2).collect()
    
    0 讨论(0)
提交回复
热议问题