1

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(???)

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

What is more important there is also implicit Ordering.comparatorToOrdering method so you don't need to make one yourself as @Harper does, just import it. See scala-lang.org/api/2.12.0/scala/math/…
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.