简体   繁体   中英

How to convert a java HashMap to immutable Scala map via java code?

I need to create a scala.collection.immutable.Map but I can't use Scala code, I have to use Java. How is it done?

I'm not looking for an empty map, I want to convert an existing Java map to an immutable Scala map.

You can use JavaConverters to do this

import java.util.HashMap;
import scala.Predef;
import scala.Tuple2;
import scala.collection.JavaConverters;
import scala.collection.immutable.Map;

public class ToScalaTest {
  public static <A, B> Map<A, B> toScalaMap(HashMap<A, B> m) {
    return JavaConverters.mapAsScalaMapConverter(m).asScala().toMap(
      Predef.<Tuple2<A, B>>conforms()
    );
  }

  public static HashMap<String, String> test() {
    HashMap<String, String> m = new HashMap<String, String>();
    m.put("a", "Stackoverflow");
    return m;
  }
}

We can show that this works in the Scala REPL

scala> val jm: java.util.HashMap[String, String] = ToScalaTest.test
jm: java.util.HashMap[String,String] = {a=Stackoverflow}

scala> val sm: Map[String, String] = ToScalaTest.toScalaMap(jm)
sm: Map[String,String] = Map(a -> Stackoverflow)

You can of course just call this methods easily from java code

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