问题描述
关于堆栈溢出问题Scala 等效于 new HashSet(Collection) ,我该如何转换将 Java 集合(例如 java.util.List
)转换为 Scala 集合 List
?
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 调用转换为 Spring 的 SimpleJdbcTemplate
,它返回一个 java.util.List
到一个 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: _*)
请注意,由于 Predef.scala
,scala.collection.immutable.Set
在默认情况下可用.
Note that scala.collection.immutable.Set
is made available by default thanks to Predef.scala
.
这篇关于将 Java 集合转换为 Scala 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!