Hey there!
Welcome to ClearUrDoubt.com.
In the below post, we have seen how to sort List objects using Ordered trait.
Sorting a List of custom objects using Ordered trait in Scala
Today we will look at a Scala program to sort MyEmployee objects based on different fields using the sortWith function defined on List.
sortWith(predicate) function takes a predicate as parameter which tells how to perform sort.
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.clearurdoubt case class MyEmployee(name: String, experience: Double, salary: Double) object EmployeeListSort { def main(args: Array[String]) { val myEmployees = List(MyEmployee("CBA", 10.0, 20000.00), MyEmployee("BCA", 9.0, 21000.00), MyEmployee("ABC", 11.0, 27000.00)) val sortedOnName = myEmployees sortWith (_.name < _.name) // Sort based on Name val sortedOnExperience = myEmployees sortWith (_.experience < _.experience) // Sort based on Experience val sortedOnSalary = myEmployees sortWith (_.salary < _.salary) // Sort based on Salary println("sortedOnName: " + sortedOnName) println println("sortedOnExperience: " + sortedOnExperience) println println("sortedOnSalary: " + sortedOnSalary) } } |
Output:
In our example, we have used a case class “MyEmployee” with three fields Name, Experience and Salary.
sortWith() function sorts the objects based the predicates provided as above.
Happy Learning :).
Please leave a reply in case of any queries.