将 Java 比较器转换为 Scala 排序

Convert Java Comparator to Scala Ordering

我正在寻找一种简单而优雅的方法来将 Java Comparator 转换为 scala Ordering

用例:

我有一个 Scala 集合,我想使用 Java 代码中定义的比较器对其进行排序:

val comparator = getComparator()
val collection = Seq("a","b")
collection.sorted(???)

如果我没记错的话,Ordering companion 包含从 Comparable[A] 到 Ordering[A] 的隐式转换:

You can import scala.math.Ordering.Implicits to gain access to other implicit orderings.

示例:

import java.util.Date

val dateOrdering = implicitly[Ordering[Date]]
import dateOrdering._

val now = new Date
val later = new Date(now.getTime + 1000L)

now < later ... should be true

到目前为止我发现的最好方法是在 java.util.Comparator 和 Ordering

之间定义您自己的隐式转换
implicit def comparatorToOrdering[T](comparator: Comparator[T]) = 
new Ordering[T] {
     def compare(x: T, y: T): Int = comparator.compare(x, y)
}

导入这个然后你就可以写了

val comparator = getComparator()
val collection = Seq("a","b")
collection.sorted(comparator)

标准库中已经存在隐式转换:scala.math.Ordering.comparatorToOrdering

您只需要导入即可使用它:

import scala.math.Ordering.comparatorToOrdering

val comparator = getComparator()
val collection = Seq("a","b")
collection.sorted(comparator)