43

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].

1

4 Answers 4

46

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
Sign up to request clarification or add additional context in comments.

2 Comments

For anyone stumbling upon this now, scala.collection.JavaConversions is deprecated since Scala 2.8. Please refer to @cyber4ron 's answer.
An important thing to note here is scala.Float is not the same type as java.lang.Float
35

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

Comments

14

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)

Comments

3
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)})

1 Comment

I did think of converting the data manually, but fortunately a more "automatic" approach is available, see the comment by pagoda_5b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.