Updated April 20, 2023
Introduction to Scala SortBy
Sorting is the process of ordering or arranging the elements in sequential or alphabetical order. Scala comes up with a special Sorting function applicable to both Mutable as well Immutable scala collection that is called as Scala Sort. SortyBy function is used to be sort one or more attributes in a Scala Collection. It sorts on the elements of a collection using a function that is defined from the user side. It belongs to the SeqLike trait. We can use various data structures over and use the sort by function to sort the collection based on the as per need. In this topic we are going to learn about Scala SortBy.
Syntax
def sortBy[B](f: (A) ⇒ B)(implicit ord: math.Ordering[B]): Repr
This SortBy takes the function and the attribute for which the sorting is to be done as the parameter.
Functioning of Sortby with Examples
SortyBy function does the sorting of elements in a mutable or immutable collection list.
Internally it uses the merge sort algorithm that divides the list of elements into parts and does the sorting over them. These goes on recursively until a sorted collection value is achieved. Sort By function takes on multiple attributes for Sorting the collection that comes with sorting the elements on the basis of the first attribute first and then following the next ones.
Let us check us with Some examples:-
Sort by With Single Attribute Case Class
scala> case class Details ( Name : String , Age :Int)
defined class Details
scala> val first = Details("Palak",10)
first: Details = Details(Palak,10)
scala> val second = Details("Gopu",4)
second: Details = Details(Gopu,4)
scala> val third = Details("Sourabh",14)
third: Details = Details(Sourabh,14)
scala> val fourth = Details("Ashish",23)
fourth: Details = Details(Ashish,23)
scala> val merge = List(first,second,third,fourth)
merge: List[Details] = List(Details(Palak,10), Details(Gopu,4), Details(Sourabh,14), Details(Ashish,23))
scala> merge.sortBy(_.Name)
res3: List[Details] = List(Details(Ashish,23), Details(Gopu,4), Details(Palak,10), Details(Sourabh,14))
scala> merge.sortBy(_.Age)
res4: List[Details] = List(Details(Gopu,4), Details(Palak,10), Details(Sourabh,14), Details(Ashish,23))
This sorting does on ascending order as per the age.
We can even do it in descending order just by adding a function .reverse() over it.
scala> merge.sortBy(_.Age).reverse
res5: List[Details] = List(Details(Ashish,23), Details(Sourabh,14), Details(Palak,10), Details(Gopu,4))
So the details here give back the Sorted value in descending order bigger age first.
Code:
One More feature we can see of sortBy operation is the preference it takes on if we have more than one SortBy function over the same collection object.
Let us check that with an Example:
Just from the above code, let’s modify and add the variable with the same name Ashish but change the age.
So the above code will be changed to:
scala> val third = Details("Ashish",14)
third: Details = Details(Ashish,14)
scala> val merge = List(first,second,third,fourth)
merge: List[Details] = List(Details(Palak,10), Details(Gopu,4), Details(Ashish,14), Details(Ashish,23))
So now the List is having two values with the same name but different age. Now let us use sortby function like this:
scala> merge.sortBy(_.Age).sortBy(_.Name)
res11: List[Details] = List(Details(Ashish,14), Details(Ashish,23), Details(Gopu,4), Details(Palak,10))
So this piece of code will sort the elements according to the Name and if the name is the same it will take the AGE as consideration. The same code when reversed the order written in sort by will behave like:-
scala> merge.sortBy(_.Name).sortBy(_.Age)
res15: List[Details] = List(Details(Gopu,4), Details(Palak,10), Details(Ashish,14), Details(Ashish,23))
Here since age are the factor in which the sorting can be performed so it is done as per age.
The above scenario is more cleared with below code:
scala> val third = Details("Ashish",4)
third: Details = Details(Ashish,4)
Now the Roll No is same for two Name i.e Gopu and Ashish
scala> val merge = List(first,second,third,fourth)
merge: List[Details] = List(Details(Palak,10), Details(Gopu,4), Details(Ashish,4), Details(Ashish,23))
scala> merge.sortBy(_.Name).sortBy(_.Age)
res17: List[Details] = List(Details(Ashish,4), Details(Gopu,4), Details(Palak,10), Details(Ashish,23))
So Sorting on the basis of Age will keep Ashish on the 1st No.
Code:
We can sort out the collection over a key, value pair also. The output after sorting a Map is a new Output generated that is stored in a new variable. The .toSeq method has sorting techniques so we can use the sortBy method by converting it into Seq. let us check that with an Example:
scala> import scala.collection.immutable.ListMap
import scala.collection.immutable.ListMap
This import is used to store the sorted value in a ListMap to maintain the order of the Sorted Map.
We created a Map Function named with Details.
scala> val details = Map("Arpit"->24,"Anand"->23,"Ram" -> 22 , "Sita" -> 22 , "David" -> 23)
details: scala.collection.immutable.Map[String,Int] = Map(Sita -> 22, David -> 23, Anand -> 23, Arpit -> 24, Ram -> 22)
The .to Seq method has the sorting method in it.
Sorting with Key
scala> details.toSeq.sortBy(_._1)
res22: Seq[(String, Int)] = ArrayBuffer((Anand,23), (Arpit,24), (David,23), (Ram,22), (Sita,22))
Sorting by Value
scala> details.toSeq.sortBy(_._2)
res23: Seq[(String, Int)] = ArrayBuffer((Sita,22), (Ram,22), (David,23), (Anand,23), (Arpit,24))
scala> val b = details.toSeq.sortBy(_._2)
b: Seq[(String, Int)] = ArrayBuffer((Sita,22), (Ram,22), (David,23), (Anand,23), (Arpit,24))
After sort the result produced In B is type ArrayBuffer so to convert it into Map we put the function in ListMap.
scala> ListMap(b:_*)
res24: scala.collection.immutable.ListMap[String,Int] = Map(Sita -> 22, Ram -> 22, David -> 23, Anand -> 23, Arpit -> 24)
Result:
scala> res24.foreach(println)
(Sita,22)
(Ram,22)
(David,23)
(Anand,23)
(Arpit,24)
Code:
So here from the above code we saw how the use of Sortby is used to Sort the various elements in a list. It is a very important concept as the sorting of the collection makes things easier for object-oriented programming.
Conclusion
Here from the above article, we got to know how sortby works in the Scala Object-Oriented Programming approach. We found how with the use of sort by the function we can help in achieving an ordered sorted collection in a very short line of code.
We got to know how sortby function in scala works with multiple attributes sorting the data accordingly. So Scala Sort By is a very concise and good approach for Scala Sorting.
Recommended Articles
We hope that this EDUCBA information on “Scala SortBy” was beneficial to you. You can view EDUCBA’s recommended articles for more information.