Converting a Java collection into a Scala collection

后端 未结 10 1524
Happy的楠姐
Happy的楠姐 2020-11-29 17:35

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 c

相关标签:
10条回答
  • 2020-11-29 18:00

    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.

    0 讨论(0)
  • 2020-11-29 18:00

    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

    0 讨论(0)
  • 2020-11-29 18:01

    JavaConversions (robinst's answer) and JavaConverters (Ben James's answer) have been deprecated with Scala 2.10.

    Instead of JavaConversions use:

    import scala.collection.convert.wrapAll._
    

    as suggested by aleksandr_hramcov.

    Instead of JavaConverters use:

    import scala.collection.convert.decorateAll._
    

    For both there is also the possibility to only import the conversions/converters to Java or Scala respectively, e.g.:

    import scala.collection.convert.wrapAsScala._
    

    Update: The statement above that JavaConversions and JavaConverters were deprecated seems to be wrong. There were some deprecated properties in Scala 2.10, which resulted in deprecation warnings when importing them. So the alternate imports here seem to be only aliases. Though I still prefer them, as IMHO the names are more appropriate.

    0 讨论(0)
  • 2020-11-29 18:13

    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)
    
    0 讨论(0)
提交回复
热议问题