Convert java.util.HashMap to scala.collection.immutable.Map in java

Viewed 17943

I'm using some Scala library from my Java code. And I have a problem with collections. I need to pass scala.collection.immutable.Map as a parameter of a method. I can convert or build immutable.Map from my Java code but I do not know how to do it. Suggestions?

7 Answers

Since I couldn't make it with Alexey's answer, I'll add that in Scala 2.13 it can be done using:

scala.collection.immutable.Map<Integer, String> scalaMap =
        scala.collection.immutable.Map.from(scala.jdk.CollectionConverters.MapHasAsScala(javaMap).asScala());

Since Scala 2.13 you can use CollectionConverters to achieve that.

Having

Map<String, String> javaMap = ...

First we convert it to mutable Scala map:

import scala.jdk.javaapi.CollectionConverters$;

var mutableScalaMap = CollectionConverters$.MODULE$.asScala(javaMap);

And then to immutable one:

var scalaMap = scala.collection.immutable.Map$.MODULE$.from(mutableScalaMap);

Simply use toMap (Scala 2.12)

import scala.collection.JavaConverters._

// asScala creates mutable Scala Map
// toMap after asScala creates immutable Map

val scalaImmutableMap = javaMap.asScala.toMap
Related