Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

Convert Java Map to Scala Map

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: the recommended way is now to use JavaConverters and the .asScala method:

import scala.collection.JavaConverters._
val myScalaMap = myJavaMap.asScala.mapValues(_.asScala.toSet)

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:

import scala.collection.JavaConversions._
val myScalaMap = myJavaMap.mapValues(_.toSet)

Calling mapValues will trigger an implicit conversion from the java Map to a scala Map, and then calling toSet on the java collection with implicitly convert it to a scala collection and then to a Set.

By default, it returns a mutable Map, you can get an immutable one with an additional .toMap.

Short-ish example:

scala> val a: java.util.Map[String, java.util.Collection[String]] = new java.util.HashMap[String, java.util.Collection[String]]
a: java.util.Map[String,java.util.Collection[String]] = {}

scala> val b = new java.util.ArrayList[String]
b: java.util.ArrayList[String] = []

scala> b.add("hi")
res5: Boolean = true

scala> a.put("a", b)
res6: java.util.Collection[String] = []

scala> import scala.collection.JavaConversions._
import scala.collection.JavaConversions._

scala> val c = a.mapValues(_.toSet)
c: scala.collection.Map[String,scala.collection.immutable.Set[String]] = Map(a -> Set(hi))

scala> c.toMap
res7: scala.collection.immutable.Map[String,scala.collection.immutable.Set[String]] = Map(a -> Set(hi))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...