Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Scala program to sort Employees objects based on their experience using Ordered trait.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.clearurdoubt class Employee(val name: String, val experience: Double, val salary: Double) extends Ordered[Employee] { override def compare(employee2: Employee) = this.experience compare employee2.experience override def toString = s"$name : $experience : $salary" } object Employee { def main(args: Array[String]) { val employees = List(new Employee("Ram", 2.09, 22000.00), new Employee("Raghu", 1.5, 20000.00), new Employee("Chaitanya", 3.2, 27000.00)) println("Employees: \n" + employees) println("Employees sorted based on experience: \n" + employees.sorted) } } |
Output:
We have to implement compare function in Ordered trait to make a custom object (i.e., Employee in our example) to be sorted based on its fields. In our example, we are interested in sorting Employees based on their experience.
Happy Learning :).
Please leave a reply in case of any queries.