将 java.util.Map[String, Object] 转换为 scala.collection.immutable.Map[String, Any]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3127238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert java.util.Map[String, Object] to scala.collection.immutable.Map[String, Any]
提问by IttayD
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 to the right value to work well in Scala.
如何将 java.util.Map[String, Object] 转换为 scala.collection.immutable.Map[String, Any],以便将原始映射中的所有值(整数、布尔值等)转换为正确的值在 Scala 中运行良好。
回答by Michel Kr?mer
As VonC says, scala.collections.JavaConversionsupports mutable collections only, but you don't have to use a separate library. Mutable collections are derived from TraversableOncewhich defines a toMapmethod that returns an immutable Map:
正如 VonC 所说,scala.collections.JavaConversion仅支持可变集合,但您不必使用单独的库。可变集合派生自TraversableOnce它定义了一个toMap返回不可变 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)
回答by VonC
The JavaConversionspackage of Scala2.8 deals only with mutable collections.
JavaConversionsScala2.8的包只处理可变集合。
The scalaj-collectionlibrary might help here.
该scalaj收集库可以帮助这里。
java.util.Map[A, B] #asScala: scala.collection.Map[A, B]
#asScalaMutable: scala.collection.mutable.Map[A, B]
#foreach(((A, B)) => Unit): Unit
回答by Dinesh Shinkar
In order to convert convert java.util.Map[String, Object] to scala.collection.immutable.Map[String,Object] , you need to simple import below statement in Scala Project and clean build.
为了将转换 java.util.Map[String, Object] 转换为 scala.collection.immutable.Map[String,Object] ,您需要在 Scala 项目中简单导入以下语句并清理构建。
import collection.JavaConversions._
Refer to below code:
参考以下代码:
var empMap= Map[String.Object]()
var emp= new Employee(empMap) // Employee is java POJO in which,passing scala map to overloaded constructor for setting default values.

