Pergunta

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!

Foi útil?

Solução

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)

Outras dicas

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]] = ()

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top