简体   繁体   中英

Convert Java Comparator to Scala Ordering

I'm looking for a simple and elegant way to convert Java Comparator to scala Ordering .

Use case:

I have a Scala collection that I want to sort using a comparator defined in Java code:

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

If I am not mistaken, the Ordering companion contains an implicit conversion from Comparable[A] to Ordering[A]:

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

Example:

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

There is already an implicit conversion in the standard library: scala.math.Ordering.comparatorToOrdering

You just need an import to use it:

import scala.math.Ordering.comparatorToOrdering

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

The best way I have found so far is to define your own implicit conversion between java.util.Comparator and Ordering

implicit def comparatorToOrdering[T](comparator: Comparator[T]) = 
new Ordering[T] {
     def compare(x: T, y: T): Int = comparator.compare(x, y)
}

Import this and then you can write

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM