The use of sorting functions in Scala



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

’s introduce their functions:

(1) sorted

sorts a collection naturally, by passing the implicit Ordering

(2) sortBy sorts

an attribute or attributes by its type.

(3) sortWith is

based on function sorting, and 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("==============sortedsorting===================")
   println(xs.sorted) //ascending
   println(xs.sorted.reverse) //descending
    println("==============sortBysort===================")
   println( xs.sortBy(d=>d) ) //ascending
   println( xs.sortBy(d=>d).reverse ) //descending order
    println("==============sortWithsort===================")
   println( xs.sortWith(_<_) )//Ascending
   println( xs.sortWith(_>_) )//descending
````
result:

````
===============sortedsorted==================
List(1, 2, 3, 4, 5, 6)
List(6, 5, 4, 3, 2, 1)
=============sortBysort==================
List(1, 2, 3, 4, 5, 6)
List(6, 5, 4, 3, 2, 1)
==============sortWithsort==================
List(1, 2, 3, 4, 5, 6)
List(6, 5, 4, 3, 2, 1)
````




Example 2: Sorting based on multiple fields of tuples

Note that of multiple fields is troublesome to use sorted. Here are examples of using sortBy and sortWith. Let’s

first look at the implementation based on sortBy:

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

   //Ascending by the third field, descending by the first field, note that the sorted fields must correspond to the following tuple
   val bx= pairs.
   sortBy(r => (r._3, r._1))( Ordering.Tuple2(Ordering.Int, Ordering.String.reverse) )
    // print the result        
    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) {//If the third field is equal, the first field is in descending order
         a._1>b._1
        }else{
        a._3<b._3 //otherwise the third field is in descending order
        }
      }
    }
    // print the result
    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

Let’s look at the implementation method of sortBy
Sorting rules: first Sort by age, if the same, then 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)

   //First sort by age, if the same, sort by name in descending order
   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 //The same age, sort by name in descending order
          case false=>person1.age<person2.age //otherwise sort by age in ascending order

        }
      }
    }

    b.map(
      println
    )
````


result:
````
Person(dog,23)
Person(cat,23)
Person(andy,25)
````



Summary:

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

sorted: suitable for ascending and descending order of 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.

In practical applications, an appropriate sorting strategy can be selected according to specific scenarios.

If you have any questions, you can scan the code and follow the WeChat public account: I am the siege division (woshigcs), leave a message in the background for consultation. Technical debts cannot be owed, and health debts cannot be owed. On the road of seeking the Tao, walk with you.

Guess you like

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