1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oh sorry, I missed the .asScala() before .toMap

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.