简体   繁体   中英

Using scala map in Java

I have two files. One is scala and other is java.

Scala file has a function which returns scala immutable map.

Java file wants to use that map as dictionary.

I am a newbie to scala and java. How can I convert that scala map to java dicionary?

HTH. Easy to do from the Scala side.

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

scala> val m = Map("one"->1)
m: scala.collection.immutable.Map[String,Int] = Map(one -> 1)

scala> val jm = m.asJava
jm: java.util.Map[String,Int] = {one=1}

scala> val hm = new java.util.Hashtable(jm)
<console>:12: error: type mismatch;
 found   : java.util.Map[String,Int]
 required: Int
       val hm = new java.util.Hashtable(jm)
                                        ^

scala> import java.util._
import java.util._

scala> val hm: Dictionary[String,Int] = new java.util.Hashtable(jm)
hm: java.util.Dictionary[String,Int] = {one=1}

Edit: Man, that was painful:

import java.util.*;

public class JavaMapper {
    public Dictionary<String, Integer> n() {
        return new Hashtable<String, Integer> (
            (Map<String, Integer>)
            scala.collection.JavaConverters$.MODULE$.mapAsJavaMapConverter((new ScalaMap().m())) // where m returns a Map, of course
        );
    }
}

This is a better way to convert a Scala immutable.Map to a Java Map in Java.

java.util.Map<String, String> javaMap = scala.collection.JavaConverters
                                           .mapAsJavaMapConverter(scalaMap).asJava();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM