Convert Scala Set into Java (java.util.Set)?

﹥>﹥吖頭↗ 提交于 2019-11-30 04:31:53

If you were asking about Scala 2.8, Java collections interoperability is supplied by scala.collection.JavaConversions. In this case, you want JavaConversions.asSet(...) (there's one for each direction, Java -> Scala and Scala -> Java).

For Scala 2.7, each scala.collection.jcl class that wraps a Java collection has an underlying property which provides the wrapped Java collection instance.

Since Scala 2.12.0 scala.collection.JavaConversions is deprecated:

Therefore, this API has been deprecated and JavaConverters should be used instead. JavaConverters provides the same conversions, but through extension methods.

And since Scala 2.8.1 you can use scala.collection.JavaConverters for this purpose:

import scala.collection.JavaConverters._
val javaSet = new java.util.HashSet[String]()
val scalaSet = javaSet.asScala
val javaSetAgain = scalaSet.asJava

For 2.7.x I highly recommend using: http://github.com/jorgeortiz85/scala-javautils

In Scala 2.12 it is possible to use : scala.collection.JavaConverters.setAsJavaSet(scalaSetInstance)

Note that starting Scala 2.13, package scala.jdk.CollectionConverters replaces deprecated packages scala.collection.JavaConverters/JavaConversions._:

import scala.jdk.CollectionConverters._

// val scalaSet: Set[String] = Set("a", "b")
val javaSet = scalaSet.asJava
// javaSet: java.util.Set[String] = [a, b]
javaSet.asScala
// scala.collection.mutable.Set[String] = Set(a, b)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!