Converting mutable to immutable map

安稳与你 提交于 2019-11-29 04:23:21

问题


private[this]object MMMap extends  HashMap[A, Set[B]] with MultiMap[A, B]

How convert it to immutable?


回答1:


The immutable hierarchy doesn't contain a MultiMap, so you won't be able to use the converted structure with the same convenient syntax. But if you're happy to deal with key/valueset pairs, then:

If you just want a mutable HashMap, you can just use x.toMap in 2.8 or collection.immutable.Map(x.toList: _*) in 2.7.

But if you want the whole structure to be immutable--including the underlying set!--then you have to do more: you need to convert the sets along the way. In 2.8:

x.map(kv => (kv._1,kv._2.toSet)).toMap

In 2.7:

collection.immutable.Map(
  x.map(kv => (kv._1,collection.immutable.Set(kv._2.toList: _*))).toList: _*
)



回答2:


scala> val mutableMap = new HashMap[Int, String]
mutableMap: scala.collection.mutable.HashMap[Int,String] = Map()

scala> mutableMap += 1 -> "a"
res5: mutableMap.type = Map((1,a))

scala> mutableMap
res6: scala.collection.mutable.HashMap[Int,String] = Map((1,a))

scala> val immutableMap = mutableMap.toMap
immutableMap: scala.collection.immutable.Map[Int,String] = Map((1,a))

scala> immutableMap += 2 -> "b"
<console>:11: error: reassignment to val
       immutableMap += 2 -> "b"
                ^



回答3:


You can use myMap.toMap to convert an a mutable map into immutable in Scala 2.8 and later versions.

Looking at definition of toMap from documentation:

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
}



回答4:


You can just to the following

val imm_map = MMMap.toMap


来源:https://stackoverflow.com/questions/2817055/converting-mutable-to-immutable-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!