How to convert java Map to scala Map of type LinkedHashMap[String,ArrayList[String]]?

前端 未结 4 1964
迷失自我
迷失自我 2020-12-21 02:42

from Java API I get

java.util.LinkedHashMap[String,java.util.ArrayList[String]]

which I then need to pass as a parameter to a scala progra

相关标签:
4条回答
  • 2020-12-21 03:27

    Just import scala.collection.JavaConversions and you should be set :) It performs conversions from Scala collections to Java collections and vice-versa.

    If it doesn't work smoothly, try:

    val m: Map[String,List[String]] = javaMap
    

    You might also need to convert each one of the lists inside the map:

    m.map {
      l => val sl: List[String] = l
      sl
    }
    
    0 讨论(0)
  • 2020-12-21 03:27
    scala.collection.JavaConversions.mapAsScalaMap
    

    or something similar in the JavaConversions Object

    0 讨论(0)
  • 2020-12-21 03:31

    You can try using

    val rmap = Foo.baz(parameter.asScala.toMap.mapValues(v => v.asScala.toList))
    

    Import below in your code -

    import scala.collection.JavaConversions._
    import scala.collection.JavaConverters._
    
    0 讨论(0)
  • 2020-12-21 03:34

    You've got two problems: Map and List in scala are different from the java versions.

    scala.collection.JavaConversions.mapAsScalaMap creates a mutable map, so using the mutable map, the following works:

    import scala.collection.JavaConversions._
    import scala.collection.mutable.Map
    
    val f = new java.util.LinkedHashMap[String, java.util.ArrayList[String]]
    var g: Map[String, java.util.ArrayList[String]] = f
    

    The ArrayList is a bit harder. The following works:

    import scala.collection.JavaConversions._
    import scala.collection.mutable.Buffer
    
    val a = new java.util.ArrayList[String]
    var b: Buffer[String] = a
    

    But if we try

    import scala.collection.JavaConversions._
    import scala.collection.mutable.Map
    import scala.collection.mutable.Buffer
    
    val f = new java.util.LinkedHashMap[String, java.util.ArrayList[String]]
    var g: Map[String, Buffer[String]] = f
    

    this doesn't work. Your best option is to define an explicit implicit conversion yourself for this.

    0 讨论(0)
提交回复
热议问题