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 program
val rmap = Foo.baz(parameter)
This parameter is of scala type:
Map[String,List[String]]
So how can I easily convert
java.util.LinkedHashMap[String,java.util.ArrayList[String]]
to
Map[String,List[String]]
I tried using import scala.collection.JavaConversions._ but in my case this does not work (or at least thats what I guess) because the scala code is in template function and I can only place import scala.collection.JavaConversions._ inside the function. the template function is like:
def someFunc(param: java.util.LinkedHashMap[String,java.util.ArrayList[String]]) = {
import scala.collection.JavaConversions._
val rmap = Foo.baz(param) // param is of scala type Map[String,List[String]]
.......
Now scala is not auto converting java type to scala type.
This is the compiler error I get: Error raised is : type mismatch; found : java.util.LinkedHashMap[String,java.util.ArrayList[String]] required: Map[String,List[String]]
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With