Convert Java Map to Scala Map

后端 未结 4 1743
傲寒
傲寒 2020-12-02 18:38

I have a java map: java.util.Map> and I would like to convert it to the scala map: Map[SomeObjec

相关标签:
4条回答
  • 2020-12-02 18:55

    Immutable Map myJavaMap.asScala.toMap

    Mutable Map myJavaMap.asScala

    0 讨论(0)
  • 2020-12-02 19:04

    If you have to do this from java:

    List<Tuple2<A, B>> tuples = javaMap.entrySet().stream()
                .map(e -> Tuple2.apply(e.getKey(), e.getValue()))
                .collect(Collectors.toList());
    
    scala.collection.Map scalaMap = scala.collection.Map$.MODULE$.apply(JavaConversions.asScalaBuffer(tuples).toSeq());
    

    Based on: https://stackoverflow.com/a/45373345/5209935

    0 讨论(0)
  • 2020-12-02 19:09

    You can convert the Java Map into Scala Map using the below function:

    val scalaMap = javaMap.asScala;
    

    For using this you need to import the import scala.collection.JavaConverters._ library.

    Hope this helps.

    0 讨论(0)
  • 2020-12-02 19:13

    Edit: the recommended way is now to use JavaConverters and the .asScala method:

    import scala.collection.JavaConverters._
    val myScalaMap = myJavaMap.asScala.mapValues(_.asScala.toSet)
    

    This has the advantage of not using magical implicit conversions but explicit calls to .asScala, while staying clean and consise.


    The original answer with JavaConversions:

    You can use scala.collection.JavaConversions to implicitly convert between Java and Scala:

    import scala.collection.JavaConversions._
    val myScalaMap = myJavaMap.mapValues(_.toSet)
    

    Calling mapValues will trigger an implicit conversion from the java Map to a scala Map, and then calling toSet on the java collection with implicitly convert it to a scala collection and then to a Set.

    By default, it returns a mutable Map, you can get an immutable one with an additional .toMap.

    Short-ish example:

    scala> val a: java.util.Map[String, java.util.Collection[String]] = new java.util.HashMap[String, java.util.Collection[String]]
    a: java.util.Map[String,java.util.Collection[String]] = {}
    
    scala> val b = new java.util.ArrayList[String]
    b: java.util.ArrayList[String] = []
    
    scala> b.add("hi")
    res5: Boolean = true
    
    scala> a.put("a", b)
    res6: java.util.Collection[String] = []
    
    scala> import scala.collection.JavaConversions._
    import scala.collection.JavaConversions._
    
    scala> val c = a.mapValues(_.toSet)
    c: scala.collection.Map[String,scala.collection.immutable.Set[String]] = Map(a -> Set(hi))
    
    scala> c.toMap
    res7: scala.collection.immutable.Map[String,scala.collection.immutable.Set[String]] = Map(a -> Set(hi))
    
    0 讨论(0)
提交回复
热议问题