Converting a java.util.Map to scala.collections.Map

While converting an Java servlet example to Scala I ran into a little snag when I had to convert a java.util.Map to a concatenated String in Scala. Actually, I initially couldn’t figure out how to convert java.util.Map to scala.collections.Map. It turned out to be very simple. Here is the code example I came up with and tested with Scala Worksheet in Eclipse. The example is a little more elaborate, because I also needed to convert the Map to a concatenated string of key value pairs. Anyway, check out the example.

import java.util.{ HashMap => JHashMap, Map => JMap }
import scala.collection.JavaConversions.mapAsScalaMap

object TestScala {
  val parameters: JMap[String, String] = new JHashMap[String, String]
  val keyValuePairList = List("param1" -> "this", "param1" -> "this", "param2" -> "is", "param3" -> "a", "param4" -> "list", "param5" -> "of", "param6" -> "parameters")
  for ((k,v) <- parameters) println(s"key: $k, value: $v")
  var s: String = ""
  for ((k,v) <- parameters) if(s.length() == 0) s += s"$k=$v" else s += s", $k=$v"

Some interesting things to note:

  • I am using aliases to import the java.util functions, i.e. HashMap => JHashMap, so that I do not have to prefix the HashMap with the package name. The alias ensures the compiler can identify it uniquely as java.util.HasMap. Pretty cool!
  • To enable conversions between Scala and Java types, simply import them from the JavaConversions object. It does all the magic for you. Try removing the import scala.collection.JavaConversions.mapAsScalaMap statement and see what happens.

Interested in more background information on JavaConversions? Check out the Scala documentation.

Happy coding!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s