Converting a Java collection into a Scala collection

后端 未结 10 1523
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 17:50
    val array = java.util.Arrays.asList("one","two","three").toArray
    
    val list = array.toList.map(_.asInstanceOf[String])
    
    0 讨论(0)
  • 2020-11-29 17:51

    Starting Scala 2.13, package scala.jdk.CollectionConverters replaces packages scala.collection.JavaConverters/JavaConversions._:

    import scala.jdk.CollectionConverters._
    
    // val javaList: java.util.List[String] = java.util.Arrays.asList("one","two","three")
    javaList.asScala
    // collection.mutable.Buffer[String] = Buffer("one", "two", "three")
    javaList.asScala.toSet
    // collection.immutable.Set[String] = Set("one", "two", "three")
    
    0 讨论(0)
  • 2020-11-29 17:53

    Another simple way to solve this problem:

    import collection.convert.wrapAll._
    
    0 讨论(0)
  • 2020-11-29 17:55

    You may also want to explore this excellent library: scalaj-collection that has two-way conversion between Java and Scala collections. In your case, to convert a java.util.List to Scala List you can do this:

    val list = new java.util.ArrayList[java.lang.String]
    list.add("A")
    list.add("B")
    list.asScala
    
    0 讨论(0)
  • 2020-11-29 17:57

    For future reference: With Scala 2.8, it could be done like this:

    import scala.collection.JavaConversions._
    val list = new java.util.ArrayList[String]()
    list.add("test")
    val set = list.toSet
    

    set is a scala.collection.immutable.Set[String] after this.

    Also see Ben James' answer for a more explicit way (using JavaConverters), which seems to be recommended now.

    0 讨论(0)
  • 2020-11-29 17:57

    If you want to be more explicit than the JavaConversions demonstrated in robinst's answer, you can use JavaConverters:

    import scala.collection.JavaConverters._
    val l = new java.util.ArrayList[java.lang.String]
    val s = l.asScala.toSet
    
    0 讨论(0)
提交回复
热议问题