Mixing Java with Scala to use mutable TreeMap

In Java, I can do something like the following:

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

If I want it to be sorted in reverse order, I can provide a comparator like

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 a mutable Java TreeMap from Scala, I can do something like this:

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

How to implement a Java comparator in Scala so that I can sort based on ascending or descending order? Here, I assume that I cannot mix the Scala Ordering symbol with the Java collection. Also, does anyone know if / when the modified TreeMap will be available in Scala?

+3
source share
2 answers

Ordering ReverseOrder :

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]) 
+6

Scala Ordering Java Comparator, :

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

Source: https://habr.com/ru/post/1789844/


All Articles