且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将scala.List转换为java.util.List?

更新时间:2023-02-14 10:25:55

Scala List和Java List是两种不同的野兽,因为前者是不可变的而后者是可变的。因此,要从一个到另一个,首先必须将Scala列表转换为可变集合。

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.

在Scala 2.7上:

On Scala 2.7:

import scala.collection.jcl.Conversions.unconvertList
import scala.collection.jcl.ArrayList
unconvertList(new ArrayList ++ List(1,2,3))

从Scala 2.8开始:

From Scala 2.8 onwards:

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
asList(ListBuffer(List(1,2,3): _*))
val x: java.util.List[Int] = ListBuffer(List(1,2,3): _*)

但是,如果预期的类型是Java 列表,则该示例中的 asList 不是必需的,因为转换是隐含的,如最后一行所示。

However, asList in that example is not necessary if the type expected is a Java List, as the conversion is implicit, as demonstrated by the last line.