Skip to Content
Course content

221: Converting Java Collections to Scala Collections

Click on the "Edit" button in the top corner of the screen to edit your slide content.

In a perfect world, every library you use would be written in pure Scala. In the real world, you're going to spend a significant amount of time interfacing with Java libraries. Whether it's a database driver or a legacy payment SDK, these libraries will hand you java.util.List, java.util.Map, or java.util.Set. The problem is that these Java collections don't have the rich functional API we love in Scala—no filter, map, or foldLeft without some awkward jumping through hoops.

The temptation to manually migrate

When I first started mixing Java and Scala, my instinct was to just "move" the data. I'd get a java.util.List back from an API, and I'd write a loop or a manual transformation to shove everything into a Scala List. It looks something like this:

import java.util.ArrayList

// Imagine this comes from a Java SDK
val javaTransactions = new ArrayList[Double]() 
javaTransactions.add(100.0)
javaTransactions.add(50.0)

// The naive way: manually building a new Scala list
var scalaList = List[Double]()
val it = javaTransactions.iterator()
while (it.hasNext) {
  scalaList = scalaList :+ it.next()
}

This is painful to write and even more painful to read. More importantly, it's inefficient. By using :+ in a loop, I'm creating a new list object on every single iteration. If that Java list has ten thousand entries, the garbage collector is going to have a very bad day. Even if you use a mutable.ArrayBuffer and then call .toList, you're still performing a full copy of the data just to get access to Scala's methods.

Wrapping instead of copying

The professional way to handle this is using scala.jdk.CollectionConverters. Instead of copying the data into a new structure, Scala provides a way to "wrap" the Java collection. This wrapper implements the Scala collection interfaces but delegates the actual data storage to the original Java object.

import scala.jdk.CollectionConverters._

val javaTransactions = new java.util.ArrayList[Double]()
javaTransactions.add(100.0)
javaTransactions.add(50.0)

// This is the magic: .asScala
val scalaTransactions = javaTransactions.asScala

// Now I have the full power of Scala
val highValue = scalaTransactions.filter(_ > 75.0).toList

Notice that .asScala doesn't actually move any elements. It creates a lightweight wrapper. This is an O(1) operation, regardless of whether the list has five elements or five million. I've seen developers avoid this because they're afraid of the "magic," but it's the standard way to bridge the two languages.

The cost of the wrapper vs. the cost of the copy

There is one critical trade-off you need to keep in mind: the wrapper is a live view. Because asScala doesn't copy the data, if the original Java list is modified by some other part of the system, your Scala wrapper will reflect those changes. This is usually what you want, but it can lead to ConcurrentModificationException if you're iterating over the Scala wrapper while another thread is mutating the Java list.

If you need a "snapshot" of the data that is guaranteed not to change, you should chain .asScala with a conversion to an immutable collection, like .toList or .toSeq. This does perform the copy, but it gives you the safety of Scala's immutability. I generally recommend .asScala` for internal transformations and .asScala.toList when the data is leaving a method and moving into a part of the app where you can't trust the source to stay static.




📋 Practical Task

Filtering Legacy Java Transaction Logs

You are working with a legacy Java accounting library that returns a java.util.Map[String, Double] where the key is a Transaction ID and the value is the amount. Your task is to process this Java map using Scala's functional tools.

Requirements:

  • Create a java.util.HashMap[String, Double] and populate it with at least four entries (e.g., "TXN001" -> 120.50, "TXN002" -> 45.00, etc.).
  • Use scala.jdk.CollectionConverters to wrap this Java map into a Scala collection.
  • Using the Scala wrapper, filter the map to keep only transactions greater than 100.00.
  • Convert the final filtered result into an immutable Scala Map.
  • Print the final immutable map to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.