Bruce Ferguson
Bruce Ferguson

Reputation: 1861

Mixing Java with Scala to use a mutable TreeMap

In Java I can do something like the following:

TreeMap<Double, String> myMap = new TreeMap<Double, String>();

If I want it sorted in reverse order, I can provide a Comparator such as:

class ReverseOrder implements Comparator<Object> {

    public ReverseOrder() {

    }

    public int compare(Object o1,Object o2) {
        Double i1=(Double)o1;
        Double i2=(Double)o2;
        return -i1.compareTo(i2);
    }
}

And instantiate the object as

TreeMap<Double, MyObject> myMap = new TreeMap<Double, MyObject>()(new ReverseOrder());

If I want to create the mutable Java TreeMap from within Scala, I can do something like this:

var treeMap = new java.util.TreeMap[Double,MyObject]

How do I implement the Java comparator in Scala so that I can sort based on ascending or descending order? Here, I'm assuming that I can't mix the Scala Ordering trait with the Java collection. Also, does anyone know if/when a mutable TreeMap is going to be available in Scala?

Upvotes: 3

Views: 1879

Answers (2)

Mike
Mike

Reputation: 1849

The Scala trait Ordering extends the Java interface Comparator, so you can do this concisely:

val treeMap = new java.util.TreeMap[Double, String](Ordering.Double.reverse)

Upvotes: 4

tenshi
tenshi

Reputation: 26586

You can use Ordering, and define ReverseOrder like this:

case class ReverseOrder[T: Ordering] extends Comparator[T] {
  def compare(o1: T, o2: T) = -implicitly[Ordering[T]].compare(o1, o2)
}

val treeMap = new TreeMap[Double, String](ReverseOrder[Double]) 

Upvotes: 6

Related Questions