문제

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!

도움이 되었습니까?

해결책

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)

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top