Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Java collection into a Scala collection

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( ... ) ) : _ *)
like image 252
oxbow_lakes Avatar asked Mar 23 '09 18:03

oxbow_lakes


3 Answers

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.

Also see Ben James' answer for a more explicit way (using JavaConverters), which seems to be recommended now.

like image 148
robinst Avatar answered Oct 16 '22 04:10

robinst


If you want to be more explicit than the JavaConversions demonstrated in robinst's answer, you can use JavaConverters:

import scala.collection.JavaConverters._
val l = new java.util.ArrayList[java.lang.String]
val s = l.asScala.toSet
like image 62
Ben James Avatar answered Oct 16 '22 02:10

Ben James


JavaConversions (robinst's answer) and JavaConverters (Ben James's answer) have been deprecated with Scala 2.10.

Instead of JavaConversions use:

import scala.collection.convert.wrapAll._

as suggested by aleksandr_hramcov.

Instead of JavaConverters use:

import scala.collection.convert.decorateAll._

For both there is also the possibility to only import the conversions/converters to Java or Scala respectively, e.g.:

import scala.collection.convert.wrapAsScala._

Update: The statement above that JavaConversions and JavaConverters were deprecated seems to be wrong. There were some deprecated properties in Scala 2.10, which resulted in deprecation warnings when importing them. So the alternate imports here seem to be only aliases. Though I still prefer them, as IMHO the names are more appropriate.

like image 25
stempler Avatar answered Oct 16 '22 04:10

stempler