Related to Stack Overflow question Scala equivalent of new HashSet(Collection) , how do I convert a Java collection (java.util.List
say) into a Scala collection List
?
I am actually trying to convert a Java API call to Spring's SimpleJdbcTemplate
, which returns a java.util.List<T>
, into a Scala immutable HashSet
. So for example:
val l: java.util.List[String] = javaApi.query( ... )
val s: HashSet[String] = //make a set from l
This seems to work. Criticism is welcome!
import scala.collection.immutable.Set
import scala.collection.jcl.Buffer
val s: scala.collection.Set[String] =
Set(Buffer(javaApi.query( ... ) ) : _ *)
Your last suggestion works, but you can also avoid using
jcl.Buffer
:Note that
scala.collection.immutable.Set
is made available by default thanks toPredef.scala
.Another simple way to solve this problem:
You can add the type information in the toArray call to make the Set be parameterized:
This might be preferable as the collections package is going through a major rework for Scala 2.8 and the scala.collection.jcl package is going away
You could convert the Java collection to an array and then create a Scala list from that:
If you want to be more explicit than the JavaConversions demonstrated in robinst's answer, you can use JavaConverters: