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 CollectionConverters 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 = javaProps.asScala
println(scalaProps)

That last line of code prints output like this:

// Map(last_name -> Carmichael, first_name -> Charles)

Notes:

  • The resulting Scala Map has the type Map[String,String].
  • Prior to Scala 2.13, the CollectionConverters object was known as JavaConverters

The Scala CollectionConverters object and Maps

In a related note, the CollectionConverters 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 CollectionConverters object over time, but until then, I hope this example is helpful.