Scala Tutorial - Learn How To Use SortBy Function With Examples
Overview
In this tutorial, we will learn how to use the sortBy function with examples on collection data structures in Scala. The sortBy function is applicable to both Scala's Mutable and Immutable collection data structures.
The sortBy method takes a predicate function and will use it to sort the elements in the collection.
As per the Scala documentation, the definition of the sortBy method is as follows:
def sortBy[B](f: (A) ⇒ B)(implicit ord: math.Ordering[B]): Repr
The sortBy method is a member of SeqLike trait.
Steps
1. How to create a case class to represent Donut objects
In the Learn how to define and use case class tutorial, we showed how to represent objects in Scala using case classes. Similarly, in the code below, we will use a case class to represent an object of type Donut.
println("\nStep 1: How to create a case class to represent Donut objects")
case class Donut(name: String, price: Double)
2. How to create a Sequence of type Donut
Using the Donut case class from Step 1, the code below shows how to create a Sequence of type donuts.
println("\nStep 2: How to create a Sequence of type Donut")
val donuts: Seq[Donut] = Seq(Donut("Plain Donut", 1.5), Donut("Strawberry Donut", 2.0), Donut("Glazed Donut", 2.5))
println(s"Elements of donuts = $donuts")
You should see the following output when you run your Scala application in IntelliJ:
Step 2: How to create a Sequence of type Donut
Elements of donuts = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2.0), Donut(Glazed Donut,2.5))
3. How to sort a sequence of case class objects using the sortBy function
The code below shows how to use the sortBy method to sort the Sequence of type donuts from Step 2. Note that we will sort each donut element by using its price property.
println("\nStep 3: How to sort a sequence of case class objects using the sortBy function")
println(s"Sort a sequence of case class objects of type Donut, sorted by price = ${donuts.sortBy(donut => donut.price)}")
You should see the following output when you run your Scala application in IntelliJ:
Step 3: How to sort a sequence of case class objects using the sortBy function
Sort a sequence of case class objects of type Donut, sorted by price = List(Donut(Plain Donut,1.5), Donut(Strawberry Donut,2.0), Donut(Glazed Donut,2.5))
Summary
In this tutorial, we went over the following:
- How to create a case class to represent Donut objects
- How to create a Sequence of type Donut
- How to sort a sequence of case class objects using the sortBy function
Tip
Source Code
The source code is available on the allaboutscala GitHub repository.
What's Next
In the next tutorial, I will show you how to use the sorted function.