不要使用mapValues
. 使用map
:
import collection.JavaConverters._
val javaMap = scalaMap.map { case (k,v) => (k, v.asJava) }.asJava
使用mapValues
将导致内部映射在每次访问时都被重新转换。
演示
斯卡拉地图
scala> val scalaMap = Map(1 -> Map('a -> "A"), 2 -> Map('b -> "B"))
转换为 Java Map(但每次转换内部 Map 时都会打印一些内容)
scala> val javaMapBad = scalaMap.mapValues(v => { println("evaluating "+v); v.asJava }).asJava
evaluating Map('a -> A)
evaluating Map('b -> B)
javaMapBad: java.util.Map[Int,java.util.Map[Symbol,java.lang.String]] = {1={'a=A}, 2={'b=B}}
scala> javaMapBad.get(1)
evaluating Map('a -> A) // Re-conversion!
res0: java.util.Map[Symbol,java.lang.String] = {'a=A}
scala> javaMapBad.get(1)
evaluating Map('a -> A) // Re-conversion!
res1: java.util.Map[Symbol,java.lang.String] = {'a=A}
正确的方法
scala> val javaMapGood = scalaMap.map{case (k,v) => {println("evaluating "+v); (k,v.asJava)}}.asJava
evaluating Map('a -> A)
evaluating Map('b -> B)
javaMapGood: java.util.Map[Int,java.util.Map[Symbol,java.lang.String]] = {1={'a=A}, 2={'b=B}}
scala> javaMapGood.get(1) // no re-conversion
res6: java.util.Map[Symbol,java.lang.String] = {'a=A}
scala> javaMapGood.get(1) // no re-conversion
res7: java.util.Map[Symbol,java.lang.String] = {'a=A}