1

What is the right way to convert a variable of type java.util.HashMap<java.lang.String, java.util.List<java.lang.String>> in Java, to its Scala equivalent: Map[Map[String, List[String]]]? (with Scala Map, String and List)

I tried to use import scala.collection.JavaConverters._ and do JavaNestedMap.asScala but it failed. Is there a smart way of doing this (rather than having two maps)?

1 Answer 1

2

There's no single call way I know of.

This is succinct likely inefficient in a hot loop. Profile if it ends up being too slow and then you'd want to use builders directly.

val in: JMap[JMap[String, String]] = ???
val out: Map[Map[String, String]] = in.asScala.mapValues(_.asScala)
val again: JMap[JMap[String, String]] = out.map(_.asJava).asJava

It's worth noting that .asScala gives you a mutable map for consistency with the java map. If you want to get an immutable map back, you need to call .toMap afterwords.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for comment. Though I think it is better to write the last two steps like this: in.asScala.map{item => (item._1, item._2.asScala.toMap)}.toMap . toMap is to convert it to Scala's immutable map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.