如何将 scala.List 转换为 java.util.List?
如何将Scala的scala.List
转换为Java的java.util.List
?
How to convert Scala's scala.List
into Java's java.util.List
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
不知道为什么之前没有提到这一点,但我认为最直观的方法是调用 JavaConverters 直接位于 Scala 列表中:
Not sure why this hasn't been mentioned before but I think the most intuitive way is to invoke the
asJava
decorator method of JavaConverters directly on the Scala list:Scala List 和 Java List 是两种不同的东西,因为前者是不可变的,后者是可变的。因此,要从一个列表转换到另一个列表,您首先必须将 Scala 列表转换为可变集合。
在 Scala 2.7 上:
从 Scala 2.8 开始:
但是,如果预期类型是 Java
List
,则该示例中的asList
不是必需的,因为转换是隐式的,如以下所示最后一行。Scala List and Java List are two different beasts, because the former is immutable and the latter is mutable. So, to get from one to another, you first have to convert the Scala List into a mutable collection.
On Scala 2.7:
From Scala 2.8 onwards:
However,
asList
in that example is not necessary if the type expected is a JavaList
, as the conversion is implicit, as demonstrated by the last line.总结之前的答案
假设我们有以下
列表
:如果您想明确并准确告诉您想要转换的内容:
如果您不想共同控制转换并让编译器为您隐式工作:
这取决于您想要如何控制代码。
To sum up the previous answers
Assuming we have the following
List
:If you want to be explicit and tell exactly what you want to convert:
If you don't want co control conversions and let compiler make implicit work for you:
It's up to you how you want to control your code.
从 Scala 2.13 开始,包
scala.jdk.CollectionConverters
提供asJava
通过Seq 并替换包
scala.collection.JavaConverters/JavaConversions
:Starting
Scala 2.13
, the packagescala.jdk.CollectionConverters
providesasJava
via a pimp ofSeq
and replaces packagesscala.collection.JavaConverters/JavaConversions
:尽管我会回答,但大多数建议都已被弃用,这是相当老的问题。
Pretty old questions, though I will answer, given but most of suggestions are deprecated.
更新
使用 scala 2.9.2
:结果
Update
with scala 2.9.2:
result
对于单次调用,手动执行可能是最简单的解决方案:
我没有测量性能。
For single invocations, doing it by hand might be the simplest solution:
I didn't measure performance.
即使在 Java 端,只要按照上面的建议进行操作也会产生不可变列表。
我发现的唯一可行的解决方案是:
Just doing as proposed above produces immutable list even on Java side.
The only working solution I've found is this:
自 Scala 2.12.0 JavaConversions 已被弃用。< /a>
所以对我来说最简单的解决方案是:
Since Scala 2.12.0 JavaConversions has been deprecated.
So the simplest solution for me was :