1

how to convert List[java.util.Map] to List[Map] in scala?

oldList:

List[java.util.Map[String,String]]

wantedList:

List[Map[String,String]]

should i new a List[Map] and loop the oldList ?

thanks!

3 Answers 3

2

Use converter methods in Scala collection package. and this is a sample to demonstrate how to convert:

import scala.collection.JavaConverters._

oldList: List[java.util.Map[String,String]]

wantedList= oldList.asScala

Edited:

as Vladimir Matveev mentioned

wantedList=oldList.map(_.asScala)
Sign up to request clarification or add additional context in comments.

1 Comment

The overall direction (usage of JavaConverters) is correct, but you have to map through the list with asScala, not just call this method on the list: oldList.map(_.asScala)
0

You could use scala.collection.JavaConversions static methods. This one adds implicit conversions from standard Java collections and allows you to perform things like this (let's assume we have already opened REPL and imported scala.collection.JavaConversions._):

scala > x
res1: java.util.HashMap[String,String] = {1=2}

scala> x.toMap
res2: scala.collection.immutable.Map[String,String] = Map(1 -> 2)

You could solve your particular problem as following:

res5: list: List[java.util.HashMap[String, String]] = ()
scala > list.map(e => e.toMap)
res6: List[scala.collection.immutable.Map[String,String]] = ()

Comments

0

JavaConverters were deprecated since Scala 2.9.0 and removed in Scala 2.11-M1 you should not use them. Instead there is a package scala.collection.convert with a module WrapAsScala. It has an implicit convertion dictionaryAsScalaMap

5 Comments

There were a few members of JavaConverters that were deprecated but JavaConverters in general is not deprecated.
@sourcedelica JavaConverters as you can see all members were deprecated
Those internal members were deprecated but everything that it inherits from DecorateAsJava and DecorateAsScala were not. The JavaConverters object itself was not, and import JavaConverters._ still works as it used to. Eg. you can do jmap.asScala.
@sourcedelica That was done for migration purposes and backward compatibility in Scala 2.11-M1 they were removed.

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.