Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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

like image 538
rjc Avatar asked Dec 22 '22 11:12

rjc


2 Answers

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.

like image 74
Matthew Farwell Avatar answered May 24 '23 22:05

Matthew Farwell


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
}
like image 33
rafalotufo Avatar answered May 24 '23 22:05

rafalotufo