Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

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

I would like to be able to perform the following, but it fails in the call to useMap. How can I perform this conversion?

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

scala> import scala.collection.JavaConverters._
import scala.collection.JavaConverters._

scala> def useMap(m: java.util.Map[java.lang.Integer, java.lang.Float]) = m
useMap: (m: java.util.Map[Integer,Float])java.util.Map[Integer,Float]

scala> val v: Map[Int, Float] = Map()
v: Map[Int,Float] = Map()

scala> useMap(v)
<console>:10: error: type mismatch;
 found   : scala.collection.immutable.Map[Int,scala.Float]
 required: java.util.Map[Integer,java.lang.Float]
              useMap(v)
                     ^

It seems to work with Map[String, String], but not Map[Int, Float].

question from:https://stackoverflow.com/questions/16583265/how-can-i-convert-scala-map-to-java-map-with-scala-float-to-java-float-k-v-conve

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...