Sort Objects using Comparable in Scala

In this example, we will show simple program about, How to sort object using Comparable in Scala. The example program has been tested and shared in the same post.

Implementing Comparable in Scala

package com.dineshkrish.scala
import java.util.ArrayList
import java.util.Collections
object Example {
def main(args: Array[String]): Unit = {
// creating array list object
var list = new ArrayList[Product]();
var prod1 = new Product(103, "Cake");
var prod2 = new Product(101, "Milk");
var prod3 = new Product(102, "Chocolate");
// adding the elements to list
list.add(prod1);
list.add(prod2);
list.add(prod3);
print("Before Sort : ");
// printing the list before sorting
println(list);
// sorting the list
Collections.sort(list);
print("After Sort : ");
// printing the list after sorting
println(list);
}
}

Product Class (Product.scala)

package com.dineshkrish.scala
class Product(prodId: Int, prodName: String) extends Comparable[Product] {
def getProdId(): Int = {
return prodId;
}
def getProdName(): String = {
return prodName;
}
override def toString(): String = {
return "[prodId : " + prodId + ", prodName : " + prodName + "]";
}
// overriding the compareTo method
override def compareTo(product: Product): Int = {
if (product.getProdId() > prodId) {
return -1;
} else if (product.getProdId() < prodId) {
return 1;
}
return 0;
}
}

Output

Before Sort : [[prodId : 103, prodName : Cake], [prodId : 101, prodName : Milk], [prodId : 102, prodName : Chocolate]]
After Sort : [[prodId : 101, prodName : Milk], [prodId : 102, prodName : Chocolate], [prodId : 103, prodName : Cake]]

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *