I have a java map: java.util.Map<SomeObject, java.util.Collection<OtherObject>>
and I would like to convert it to the scala map: Map[SomeObject, Set[OtherObject]]
I have used mapAsScalaMap but the result is not quite what I want, the result is: Map[SomeObject, java.util.Collection[OtherObject]]
. How can I fix it to also convert the collection to a set?
NOTE: actually my original problem was to convert google's ArrayListMultimap<SomeObject, OtherObject>
to a MultiMap[SomeObject, OtherObject]
but since this was not possible I've split the problem. If you have a solution for the original problem, I'll also accept it as the answer.
Edit: the recommended way is now to use
JavaConverters
and the.asScala
method:This has the advantage of not using magical implicit conversions but explicit calls to
.asScala
, while staying clean and consise.The original answer with
JavaConversions
:You can use
scala.collection.JavaConversions
to implicitly convert between Java and Scala:Calling
mapValues
will trigger an implicit conversion from the javaMap
to a scalaMap
, and then callingtoSet
on the java collection with implicitly convert it to a scala collection and then to aSet
.By default, it returns a mutable
Map
, you can get an immutable one with an additional.toMap
.Short-ish example:
Immutable Map
myJavaMap.asScala.toMap
Mutable Map
myJavaMap.asScala
You can convert the Java Map into Scala Map using the below function:
For using this you need to import the import scala.collection.JavaConverters._ library.
Hope this helps.
If you have to do this from java:
Based on: https://stackoverflow.com/a/45373345/5209935