Converting a Java collection into a Scala collecti

2019-01-07 03:56发布

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( ... ) ) : _ *)

9条回答
仙女界的扛把子
2楼-- · 2019-01-07 04:25

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.

查看更多
叼着烟拽天下
3楼-- · 2019-01-07 04:25
val array = java.util.Arrays.asList("one","two","three").toArray

val list = array.toList.map(_.asInstanceOf[String])
查看更多
三岁会撩人
4楼-- · 2019-01-07 04:25

Another simple way to solve this problem:

import collection.convert.wrapAll._
查看更多
可以哭但决不认输i
5楼-- · 2019-01-07 04:31

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

查看更多
我命由我不由天
6楼-- · 2019-01-07 04:34

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)
查看更多
beautiful°
7楼-- · 2019-01-07 04:39

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
查看更多
登录 后发表回答