我有一个特定类的对象向量。如何对它们进行排序?我需要在类中添加哪个比较方法才能使其可排序?如果没有这种方法,我应该实现哪个排序函数?
我有一个特定类的对象向量。如何对它们进行排序?我需要在类中添加哪个比较方法才能使其可排序?如果没有这种方法,我应该实现哪个排序函数?
Vector
的sorted
方法需要一个类型为math.Ordering[B]
的隐式参数,用于排序。有几种提供它的方式:
Define an implicit math.Ordering[MyClass]
. You can create an Ordering
for your class using the methods from the Ordering
companion object:
case class MyClass(field: Int)
object MyClass {
implicit val MyClassOrdering: Ordering[MyClass] = Ordering.by(_.field)
}
If the Ordering
is defined in the companion object of MyClass
, it'll be provided for sorting automatically. Otherwise, you'll have to import it manually before calling sorted
. Ordering
allows 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 overriding compare
method. In this case the necessary Ordering
will 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 sortBy
or sortWith
methods of Vector
, which take a function and don't need an Ordering
parameter.
vectorOfMyClass.sortBy(_.field)
vectorOfMyClass.sortWith(_.field < _.field)