Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java.util.HashMap to scala.collection.immutable.Map in java

Tags:

I'm using some Scala library from my Java code. And I have a problem with collections. I need to pass scala.collection.immutable.Map as a parameter of a method. I can convert or build immutable.Map from my Java code but I do not know how to do it. Suggestions?

like image 608
user1590420 Avatar asked Aug 10 '12 13:08

user1590420


1 Answers

It's entirely possible to use JavaConverters in Java code—there are just a couple of additional hoops to jump through:

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 show that this works from the 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 could just as easily call these methods from Java code.

like image 116
Travis Brown Avatar answered Sep 28 '22 04:09

Travis Brown