The use of collection sorting function in scala

Sorting methods are very common in practical application scenarios. There are three sorting methods in Scala, namely: sorted, sortBy, sortWith

Introduce their functions separately:

(1)sorted

Naturally sort a collection by passing the implicit Ordering

(2)sortBy

Sorts an attribute or attributes by its type.

(3)sortWith

Function-based sorting implements the logic of custom sorting through a comparator function.

Example 1: Sorting based on a single set and a single field

val xs=Seq(1,5,3,4,6,2)
    println("==============sorted排序=================")
   println(xs.sorted) //升序
   println(xs.sorted.reverse) //降序
    println("==============sortBy排序=================")
   println( xs.sortBy(d=>d) ) //升序
   println( xs.sortBy(d=>d).reverse ) //降序
    println("==============sortWith排序=================")
   println( xs.sortWith(_<_) )//升序
   println( xs.sortWith(_>_) )//降序

result:

==============sorted排序=================
List(1, 2, 3, 4, 5, 6)
List(6, 5, 4, 3, 2, 1)
==============sortBy排序=================
List(1, 2, 3, 4, 5, 6)
List(6, 5, 4, 3, 2, 1)
==============sortWith排序=================
List(1, 2, 3, 4, 5, 6)
List(6, 5, 4, 3, 2, 1)

Example 2: Sorting based on tuple multi-field

Pay attention to the sorting of multiple fields, it is more troublesome to use sorted, here are examples of using sortBy and sortWith

First look at the implementation based on sortBy:

val pairs = Array(
                      ("a", 5, 1),
                      ("c", 3, 1),
                      ("b", 1, 3)
                       )

   //按第三个字段升序,第一个字段降序,注意,排序的字段必须和后面的tuple对应
   val bx= pairs.
   sortBy(r => (r._3, r._1))( Ordering.Tuple2(Ordering.Int, Ordering.String.reverse) )
    //打印结果        
    bx.map( println )

result:

(c,3,1)
(a,5,1)
(b,1,3)

Look at the implementation based on sortWith:

val pairs = Array(
                      ("a", 5, 1),
                      ("c", 3, 1),
                      ("b", 1, 3)
                       )
       val b= pairs.sortWith{
      case (a,b)=>{
        if(a._3==b._3) {//如果第三个字段相等,就按第一个字段降序
         a._1>b._1
        }else{
        a._3<b._3 //否则第三个字段降序
        }
      }
    }
    //打印结果
    b.map(println)

As can be seen from the above, the second implementation based on sortBy is more elegant, with clearer semantics, and the third is more flexible, but the code is slightly more cumbersome

Example 3: Class-Based Sorting

First look at the implementation method of sortBy Sorting rules: first sort by age, if the same, sort by name in descending order

case class Person(val name:String,val age:Int)

    val p1=Person("cat",23)
    val p2=Person("dog",23)
    val p3=Person("andy",25)
    
    val pairs = Array(p1,p2,p3)

   //先按年龄排序,如果一样,就按照名称降序排
   val bx= pairs.sortBy(person => (person.age, person.name))( Ordering.Tuple2(Ordering.Int, Ordering.String.reverse) )

    bx.map(
      println
    )

result:

Person(dog,23)
Person(cat,23)
Person(andy,25)

Look at the implementation method of sortWith:

case class Person(val name:String,val age:Int)

    val p1=Person("cat",23)
    val p2=Person("dog",23)
    val p3=Person("andy",25)

    val pairs = Array(p1,p2,p3)

    val b=pairs.sortWith{
      case (person1,person2)=>{
        person1.age==person2.age match {
          case true=> person1.name>person2.name //年龄一样,按名字降序排
          case false=>person1.age<person2.age //否则按年龄升序排

        }
      }
    }

    b.map(
      println
    )

result:

Person(dog,23)
Person(cat,23)
Person(andy,25)

Summarize:

This article introduces three sorting functions in scala, each of which has its own application scenarios:

sorted: ascending and descending order suitable for a single collection

sortBy: suitable for sorting single or multiple attributes, the amount of code is relatively small, it is recommended to use this

sortWith: It is suitable for high-level sorting rules in customized scenarios. It is more flexible and can also support sorting of single or multiple attributes, but the amount of code is slightly larger. The internal sorting is actually done through the Comparator interface in java.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324939917&siteId=291194637