convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any]

后端 未结 3 1760
我寻月下人不归
我寻月下人不归 2021-01-01 10:10

How do I convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any], so that all values in the original map (integers, booleans etc.) are converted

3条回答
  •  萌比男神i
    2021-01-01 10:52

    As VonC says, scala.collections.JavaConversion supports mutable collections only, but you don't have to use a separate library. Mutable collections are derived from TraversableOnce which defines a toMap method that returns an immutable Map:

    import scala.collection.JavaConversions._
    
    val m = new java.util.HashMap[String, Object]()
    m.put("Foo", java.lang.Boolean.TRUE)
    m.put("Bar", java.lang.Integer.valueOf(1))
    
    val m2: Map[String, Any] = m.toMap
    println(m2)
    

    This will output

    Map(Foo -> true, Bar -> 1)
    

提交回复
热议问题