如何将可变 HashMap 转换为 Scala 中的不可变等价物?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9058070/
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
How to convert a mutable HashMap into an immutable equivalent in Scala?
提问by Ivan
Inside a function of mine I construct a result set by filling a new mutable HashMap with data (if there is a better way - I'd appreciate comments). Then I'd like to return the result set as an immutable HashMap. How to derive an immutable from a mutable?
在我的一个函数中,我通过用数据填充一个新的可变 HashMap 来构造一个结果集(如果有更好的方法 - 我很感激评论)。然后我想将结果集作为不可变的 HashMap 返回。如何从可变的派生不可变的?
采纳答案by dhg
scala> val m = collection.mutable.HashMap(1->2,3->4)
m: scala.collection.mutable.HashMap[Int,Int] = Map(3 -> 4, 1 -> 2)
scala> collection.immutable.HashMap() ++ m
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)
or
或者
scala> collection.immutable.HashMap(m.toSeq:_*)
res2: scala.collection.immutable.HashMap[Int,Int] = Map(1 -> 2, 3 -> 4)
回答by ebruchez
Discussion about returning immutable.Mapvs. immutable.HashMapnotwithstanding, what about simply using the toMapmethod:
关于返回immutable.Map与immutable.HashMap尽管的讨论,简单地使用该toMap方法怎么样:
scala> val m = collection.mutable.HashMap(1 -> 2, 3 -> 4)
m: scala.collection.mutable.HashMap[Int,Int] = Map(3 -> 4, 1 -> 2)
scala> m.toMap
res22: scala.collection.immutable.Map[Int,Int] = Map(3 -> 4, 1 -> 2)
As of 2.9, this uses the method toMapin TraversableOnce, which is implemented as follows:
作为2.9,这里采用的方法toMap中TraversableOnce,这是如下实现的:
def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = {
val b = immutable.Map.newBuilder[T, U]
for (x <- self)
b += x
b.result
}
回答by Sandeep Das
If you have a map : logMap: Map[String, String]just need to do : logMap.toMap()
如果您有地图:logMap: Map[String, String]只需要做:logMap.toMap()

