4
votes

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]]

4

4 Answers

5
votes

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
}
5
votes

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.

1
votes
scala.collection.JavaConversions.mapAsScalaMap

or something similar in the JavaConversions Object

0
votes

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._