How to convert Java Properties to a Scala Map

Here’s a quick look at how to convert a Java Properties collection (java.util.Properties) to a Scala Map using Scala’s JavaConverters object:

// create Java Properties
import java.util._
val javaProps = new Properties
javaProps.put("first_name", "Adam")
javaProps.put("last_name", "Scott")

// convert Java Properties to Scala Map
import scala.collection.JavaConverters._
val scalaProps = p.asScala

Skipping the import statements, here’s what that looks like in the Scala REPL:

scala> val javaProps = new Properties
javaProps: java.util.Properties = {}

scala> javaProps.put("first_name", "Adam")
res2: Object = null

scala> javaProps.put("last_name", "Scott")
res3: Object = null

scala> val scalaProps = p.asScala
scalaProps: scala.collection.mutable.Map[String,String] = 
    Map(last_name -> Scott, first_name -> Adam)

Notice that the resulting Scala Map has the type Map[String,String].

The Scala JavaConverters object and Maps

In a related note, 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 ...