Add Java util. HashMap is converted to scala. XML in Java collection. immutable. Map

I used some Scala libraries from my java code I have a collection problem I need to pass Scala collection. immutable. Map as a parameter of the method I can convert from my java code or build immutable Map, but I don't know what to do Suggestions?

Solution

You can use javaconverters in Java code – just a few extra jumps to skip:

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

public class ToScalaExample {
  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> example() {
    HashMap<String,String> m = new HashMap<String,String>();
    m.put("a","A");
    m.put("b","B");
    m.put("c","C");
    return m;
  }
}

We can prove this from Scala repl:

scala> val jm: java.util.HashMap[String,String] = ToScalaExample.example
jm: java.util.HashMap[String,String] = {b=B,c=C,a=A}

scala> val sm: Map[String,String] = ToScalaExample.toScalaMap(jm)
sm: Map[String,String] = Map(b -> B,c -> C,a -> A)

But of course, you can easily call these methods from Java code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>