nyuwec
nyuwec

Reputation: 481

Is there a better way to convert a Scala Map to Java Map?

I found a solution, but it is not too elegant:

mapAsJavaMap(Map("param1"->someObject, "param2"->otherObject ))

I found some examples containing "asJava" calls, but it is not working in my configuration of Scala 2.10.X.

Upvotes: 1

Views: 2991

Answers (1)

Lauri
Lauri

Reputation: 4800

There is object JavaConverters that will do the trick for you:

import scala.collection.JavaConverters.mapAsJavaMapConverter

Map("param1"-> 1, "param2"-> 2).asJava
//> res0: java.util.Map[String,Int] = {param1=1, param2=2}

Edit: It is indeed a bad programming habbit to use wildcard imports as they will clutter your namespace and they might introduce accidental implicit conversion/values into the scope. So changed wildcard import to explicit import.

Upvotes: 6

Related Questions