如何在Scala中对对象向量进行排序?

3

我有一个特定类的对象向量。如何对它们进行排序?我需要在类中添加哪个比较方法才能使其可排序?如果没有这种方法,我应该实现哪个排序函数?


1
可能是重复的问题:https://stackoverflow.com/questions/4981818/sort-vector-of-objects-in-scala - Akos Krivachy
1个回答

4

Vectorsorted方法需要一个类型为math.Ordering[B]的隐式参数,用于排序。有几种提供它的方式:

  1. 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.

  2. 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.

  3. 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)
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接