views:

5416

answers:

6

Related to this question, how do convert a Java collection (java.util.List say) into a scala collection List?

EDIT; what I am actually trying to do is 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

EDIT AGAIN. This seems to work. Criticism welcome!

import scala.collection.immutable.Set
import scala.collection.jcl.Buffer 
val s: scala.collection.Set[String] =
                      Set(Buffer(javaApi.query( ... ) ) : _ *)
+1  A: 

You could convert the Java collection to an array and then create a Scala list from that:

val array = java.util.Arrays.asList("one","two","three").toArray
val list = List.fromArray(array)
Fabian Steeg
This isn't great because my java.util.List is coming back out of a Java API as a parametrized list (so my call to the API yields a java.util.List<String>) - I'm trying to turn this into a scala immutable HashSet
oxbow_lakes
+3  A: 

Your last suggestion works, but you can also avoid using jcl.Buffer:

Set(javaApi.query(...).toArray : _*)

Note that scala.collection.immutable.Set is made available by default thanks to Predef.scala

Jorge Ortiz
This suggestion doesn't work where I want to keep the type information
oxbow_lakes
+2  A: 

You can add the type information in the toArray call to make the Set be parameterized:

 val s = Set(javaApi.query(....).toArray(new Array[String](0)) : _*)

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

Aaron
+4  A: 

You may also want to explore this excellent library: scalaj-collection that has two-way conversion between Java and Scala collections. In your case, to convert a java.util.List to Scala List you can do this:

val list = new java.util.ArrayList[java.lang.String]
list.add("A")
list.add("B")
list.asScala
Surya Suravarapu
That library is the greatest thing ever. Really really works well.
Michael Neale
A: 
val array = java.util.Arrays.asList("one","two","three").toArray

val list = array.toList.map(_.asInstanceOf[String])
jamesqiu
A: 

For future reference: With Scala 2.8, it could be done like this:

import scala.collection.JavaConversions._
val list = new java.util.ArrayList[String]()
list.add("test")
val set = list.toSet

set is a scala.collection.immutable.Set[String] after this.

robinst