How to convert a Java Map to a Scala Map using JavaConverters

Here’s a quick look at how to convert a Java Map (such as HashMap) to a Scala Map using the JavaConverters object:

// import what you need
import java.util._
import scala.collection.JavaConverters._

// create and populate a java map
val jMap = new HashMap[String, String]()
jMap.put("first_name", "Alvin")
jMap.put("last_name",  "Alexander")

// convert the java map to a scala map
val sMap = jMap.asScala

The key there is knowing that importing the JavaConverters object creates a method named asScala on the Java Map, and that method creates a Scala Map from the Java Map.

A second key is knowing that the JavaConversions object is deprecated, and you should use JavaConverters instead of JavaConversions.

UPDATE: In Scala 2.13 the JavaConverters class was moved to scala.jdk.CollectionConverters.

Example in the REPL

Here’s what that sequence looks like in the Scala REPL:

scala> import java.util._
import java.util._

scala> import scala.collection.JavaConverters._
import scala.collection.JavaConverters._

scala> val jMap = new HashMap[String, String]()
jMap: java.util.HashMap[String,String] = {}

scala> jMap.put("first_name", "Alvin")
res3: String = null

scala> jMap.put("last_name",  "Alexander")
res4: String = null

scala> val sMap = jMap.asScala
sMap: scala.collection.mutable.Map[String,String] = 
    Map(last_name -> Alexander, first_name -> Alvin)


As shown, that creates a Scala mutable Map. If you need an immutable Map, just call toMap (which is a normal Scala method on a mutable Map, and has nothing to do with JavaConverters):

scala> val iMap = sMap.toMap
iMap: scala.collection.immutable.Map[String,String] = 
    Map(last_name -> Alexander, first_name -> Alvin)


The JavaConverters object also lets you convert a Scala Map to a Java Map using asJava:

scala> val jMap2 = iMap.asJava
jMap2: java.util.Map[String,String] = {last_name=Alexander, first_name=Alvin}

The Scala JavaConverters object and Maps

The JavaConverters scaladoc shows that you can make the following conversions to/from Java and Scala map-related types using asScala, asJava, and asJavaDictionary:

// asScala and asJava
scala.collection.mutable.Map    <=> java.util.Map
scala.collection.concurrent.Map <=> java.util.concurrent.ConcurrentMap

// asScala, asJavaDictionary
scala.collection.mutable.Map <=> java.util.Dictionary

// asJava
scala.collection.Map => java.util.Map

I’ll write more about the Scala JavaConverters object over time, but until then, I hope this example is helpful.

... this post is sponsored by my books ...