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 c
val array = java.util.Arrays.asList("one","two","three").toArray
val list = array.toList.map(_.asInstanceOf[String])
Starting Scala 2.13
, package scala.jdk.CollectionConverters replaces packages scala.collection.JavaConverters/JavaConversions._
:
import scala.jdk.CollectionConverters._
// val javaList: java.util.List[String] = java.util.Arrays.asList("one","two","three")
javaList.asScala
// collection.mutable.Buffer[String] = Buffer("one", "two", "three")
javaList.asScala.toSet
// collection.immutable.Set[String] = Set("one", "two", "three")
Another simple way to solve this problem:
import collection.convert.wrapAll._
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
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.
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