问题描述
我正在使用Java代码中的一些Scala库。我收藏有问题。我需要传递 scala.collection.immutable.Map
作为方法的参数。我可以从我的Java代码转换或构建 immutable.Map
,但我不知道该怎么做。建议?
I'm using some Scala library from my Java code. And I have a problem with collections. I need to pass scala.collection.immutable.Map
as a parameter of a method. I can convert or build immutable.Map
from my Java code but I do not know how to do it. Suggestions?
推荐答案
在Java代码中完全可以使用 JavaConverters
- 只有几个额外的环节可以跳过:
It's entirely possible to use JavaConverters
in Java code—there are just a couple of additional hoops to jump through:
import java.util.HashMap;
import scala.Predef;
import scala.Tuple2;
import scala.collection.JavaConverters;
import scala.collection.immutable.Map;
public class ToScalaExample {
public static <A, B> Map<A, B> toScalaMap(HashMap<A, B> m) {
return JavaConverters.mapAsScalaMapConverter(m).asScala().toMap(
Predef.<Tuple2<A, B>>conforms()
);
}
public static HashMap<String, String> example() {
HashMap<String, String> m = new HashMap<String, String>();
m.put("a", "A");
m.put("b", "B");
m.put("c", "C");
return m;
}
}
我们可以证明这适用于Scala REPL:
We can show that this works from the Scala REPL:
scala> val jm: java.util.HashMap[String, String] = ToScalaExample.example
jm: java.util.HashMap[String,String] = {b=B, c=C, a=A}
scala> val sm: Map[String, String] = ToScalaExample.toScalaMap(jm)
sm: Map[String,String] = Map(b -> B, c -> C, a -> A)
但是你当然可以从Java代码中轻松调用这些方法。
But of course you could just as easily call these methods from Java code.
这篇关于将java.util.HashMap转换为java中的scala.collection.immutable.Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!