Scala3 — Convert to and from Java collections in Scala code — scala.jdk.CollectionConverters._

zeesh.arif
2 min readDec 11, 2023

Since Scala can run on the Java Virtual Machine and interoperate with java code and classes, therefore it is important to have some understanding of conversion from and to Scala and Java collections.

Just like Scala, Java also has a rich library of Collections to work with. Following are some of the Collection types in Java:

  1. java.util.List
  2. java.util.Set
  3. java.util.Map…

Most of Java collections map to mutable collections in Scala. Following is the mapping between collections in both programming languages:

  1. scala.collection.Iterable < == > java.lang.Iterable
  2. scala.collection.Iterator < == > java.util.Iterator
  3. scala.collection.mutable.Buffer < == > java.util.List
  4. scala.collection.mutable.Set < == > java.util.Set
  5. scala.collection.mutable.Map < == > java.util.Map
  6. scala.collection.concurrent.Map < == > java.util.concurrent.ConcurrentMap

We will discuss the scala.jdk.CollectionConverters object which deals with converting between Scala and Java collections while writing Scala code. When writing Java code, the programmer should use scala.jdk.javaapi.CollectionConverters to convert between Scala and Java collections.

Consider the following code snippet:

import scala.jdk.CollectionConverters._

val mutableScalaSet = collection.mutable.Set("one")

val javaSet = mutableScalaSet.asJava

javaSet.add("two")

mutableScalaSet //output res8: scala.collection.mutable.Set[String] = HashSet(two, one)

First we create a mutable Scala set and convert it into a java.util.Set object using .asJava method. This conversion returns an adapter for the Scala set. This means that the Scala collection is only wrapped inside a Java Set object and not actually converted; this can be confirmed when we add “two” to the javaSet object but it is also added to the mutableScalaSet object (see output).

Once created, the javaSet can be passed to any Java object which accepts a java.util.Set object for any computation.

Following conversions are also supported using asScala methods and through specially-named extension methods

scala.collection.Iterable < == > java.util.Collection (via as JavaCollection)

scala.collection.Iterator < == > java.util.Enumeration (via asJavaEnumeration)

scala.collection.mutable.Map < == > java.util.Dictionary (via asJavaDictionary)

Finally, converting from a source type to target type and back again will retrun the original source object.

For more on CollectionConverters object, please review the scaladoc @ https://www.scala-lang.org/api/3.3.1/scala/jdk/CollectionConverters$.html

--

--