How to convert a scala.List to a java.util.List?
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> val scalaList = List(1,2,3)scalaList: List[Int] = List(1, 2, 3)scala> import scala.collection.JavaConverters._import scala.collection.JavaConverters._scala> scalaList.asJavares11: java.util.List[Int] = [1, 2, 3]
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:
import scala.collection.jcl.Conversions.unconvertListimport scala.collection.jcl.ArrayListunconvertList(new ArrayList ++ List(1,2,3))
From Scala 2.8 onwards:
import scala.collection.JavaConversions._import scala.collection.mutable.ListBufferasList(ListBuffer(List(1,2,3): _*))val x: java.util.List[Int] = ListBuffer(List(1,2,3): _*)
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.
To sum up the previous answers
Assuming we have the following List
:
scala> val scalaList = List(1,2,3)scalaList: List[Int] = List(1, 2, 3)
If you want to be explicit and tell exactly what you want to convert:
scala> import scala.collection.JavaConverters._import scala.collection.JavaConverters._scala> scalaList.asJavares11: java.util.List[Int] = [1, 2, 3]
If you don't want co control conversions and let compiler make implicit work for you:
scala> import scala.collection.JavaConversions._import scala.collection.JavaConversions._scala> val javaList: java.util.List[Int] = scalaListjavaList: java.util.List[Int] = [1, 2, 3]
It's up to you how you want to control your code.