问题描述
与Stack Overflow问题相关 ,如何转换Java集合( java.util.List
说)到Scala集合列表
?
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
?
我实际上是在尝试将Java API调用转换为 SimpleJdbcTemplate
,它将 java.util.List< T>
返回到Scala不可变 HashSet的
。例如:
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( ... ) ) : _ *)
推荐答案
您的上一个建议有效,但您也可以避免使用 jcl.Buffer
:
Your last suggestion works, but you can also avoid using jcl.Buffer
:
Set(javaApi.query(...).toArray: _*)
请注意,默认情况下, scala.collection.immutable.Set
可用 Predef.scala
。
Note that scala.collection.immutable.Set
is made available by default thanks to Predef.scala
.
这篇关于将Java集合转换为Scala集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!