I have a Vector of objects of a particular class. How can I sort them? Which comparison method must I add to a class to make it sortable? If not method, which ordering function should I implement?
1 Answer
Method sorted of Vector takes an implicit parameter of type math.Ordering[B], which it uses for sorting. There are several ways to provide it:
Define an implicit
math.Ordering[MyClass]. You can create anOrderingfor your class using the methods from theOrderingcompanion object:case class MyClass(field: Int) object MyClass { implicit val MyClassOrdering: Ordering[MyClass] = Ordering.by(_.field) }If the
Orderingis defined in the companion object ofMyClass, it'll be provided for sorting automatically. Otherwise, you'll have to import it manually before callingsorted.Orderingallows to provide several different ordering defined on a class, and to import or provide explicitly the one you want.Have your class extend
Ordered[MyClass]by overridingcomparemethod. In this case the necessaryOrderingwill be created implicitly.case class MyClass(field: Int) extends Ordered[MyClass] { def compare(other: MyClass): Int = this.field compareTo other.field }This will also add methods
<,>,<=,>=to the class.Use
sortByorsortWithmethods ofVector, which take a function and don't need anOrderingparameter.vectorOfMyClass.sortBy(_.field) vectorOfMyClass.sortWith(_.field < _.field)