将 Java 与 Scala 混合以使用可变 TreeMap
在 Java 中,我可以执行如下操作:
TreeMap<Double, String> myMap = new TreeMap<Double, String>();
如果我希望按相反的顺序排序,我可以提供一个比较器,例如:
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);
}
}
并将对象实例化为
TreeMap<Double, MyObject> myMap = new TreeMap<Double, MyObject>()(new ReverseOrder());
如果我想从 Scala 中创建可变的 Java TreeMap,我可以执行类似的操作this:
var treeMap = new java.util.TreeMap[Double,MyObject]
如何在 Scala 中实现 Java 比较器,以便可以按升序或降序排序?在这里,我假设我无法将 Scala Ordering 特性与 Java 集合混合在一起。另外,有谁知道 Scala 中是否/何时提供可变 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
Ordering
,并定义ReverseOrder
,如下所示:You can use
Ordering
, and defineReverseOrder
like this:Scala 特性
Ordering
扩展了 Java 接口Comparator
,因此您可以简洁地执行此操作:The Scala trait
Ordering
extends the Java interfaceComparator
, so you can do this concisely: