Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 807
rvange Avatar asked May 16 '13 09:05

rvange


People also ask

Can we convert map to set Java?

To convert, Java Map to Set , we can use the conventional constructor with HashSet , however, there are few things to consider before we proceed with the conversion.

How do I convert a list to map in Scala?

In Scala, you can convert a list to a map in Scala using the toMap method. A map contains a set of values i.e. key-> value but a list contains single values. So, while converting a list to map we have two ways, Add index to list.

Is map immutable in Scala?

Maps are classified into two types: mutable and immutable. By default Scala uses immutable Map. In order to use mutable Map, we must import scala.

Is Scala map a HashMap?

HashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map.


2 Answers

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 
like image 148
rvange Avatar answered Oct 03 '22 01:10

rvange


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 
like image 39
cyber4ron Avatar answered Oct 03 '22 01:10

cyber4ron