只有引入隐式转换类 JavaConverters,才能使用Scala集合与Java集合之间的转换函数。
为方便理解,看下面的例子:
import scala.collection.JavaConverters._
val javaList = java.util.Arrays.asList("hi", "bye")
val scalaBuffer = javaList.asScala
val scalaIterator = Iterator(1,2,3)
val javaIterator = scalaIterator.asJava
val javaEnumeration = scalaIterator.asJavaEnumeration
集合之间互转默认使用asScala和asScala,特殊的在表格中做了标记。其中 <=> 代表可以互转,而 => 和 <= 代表只能单方向转换。
Scala集合 | 转换方向 | Java集合 |
---|---|---|
scala.collection.Iterable | <=> | java.lang.Iterable |
scala.collection.Iterator | <=> | java.util.Iterator |
scala.collection.mutable.Buffer | <=> | java.util.List |
scala.collection.mutable.Set | <=> | java.util.Set |
scala.collection.mutable.Map | <=> | java.util.Map |
scala.collection.concurrent.Map | <=> | java.util.concurrent.ConcurrentMap |
scala.collection.Iterable | <=> | java.util.Collection (via asJavaCollection) |
scala.collection.Iterator | <=> | java.util.Enumeration (via asJavaEnumeration) |
scala.collection.mutable.Map | <=> | java.util.Dictionary (via asJavaDictionary) |
scala.collection.Seq | => | java.util.List |
scala.collection.mutable.Seq | => | java.util.List |
scala.collection.Set | => | java.util.Set |
scala.collection.Map | => | java.util.Map |
scala.collection.mutable.Map | <= | java.util.Properties |