How can I convert Scala Map to Java Map with scala.Float to java.Float k/v conversion

做~自己de王妃 提交于 2019-11-30 04:15:02
cyber4ron

Use scala predefined float2Float and use CollectionConverters to perform conversion explicitly.

import scala.jdk.CollectionConverters._
// Prior to Scala 2.13: import scala.collection.JavaConverters._
val scalaMap = Map(1 -> 1.0F)
val javaMap = scalaMap.map{ case (k, v) => k -> float2Float(v) }.asJava
rvange

The solution linked to by @pagoda_5b works: Scala convert List[Int] to a java.util.List[java.lang.Integer]

scala> import collection.JavaConversions._
import collection.JavaConversions._

scala> val m = mapAsJavaMap(Map(1 -> 2.1f)).asInstanceOf[java.util.Map[java.lang.Integer, java.lang.Float]]
m: java.util.Map[Integer,Float] = {1=2.1}

scala> m.get(1).getClass
res2: Class[_ <: Float] = class java.lang.Float

Implicit conversions are sometimes hard to debug/understand and therefore I prefer explicit conversions as follows:

import scala.collection.JavaConversions.mapAsJavaMap

val scalaMap = Map(1 -> 1.0F)
val javaMap = mapAsJavaMap(scalaMap)
scala> v.asJava
<console>:16: error: type mismatch;
 found   : java.util.Map[Int,scala.Float]
 required: java.util.Map[Integer,java.lang.Float]

The type of v is Map[scala.Int, scala.Float], not Map[java.lang.Integer, java.lang.Float].

You could try this:

import java.lang.{Float => JFloat}
useMap(v.map{ case (k, v) => (k: Integer) -> (v: JFloat)})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!