Mutable MultiMap to immutable Map

二次信任 提交于 2019-12-23 13:26:14

问题


I create a MultiMap

val ms =
  new collection.mutable.HashMap[String, collection.mutable.Set[String]]()
  with collection.mutable.MultiMap[String, String]

which, after it has been populated with entries, must be passed to a function that expects a Map[String, Set[String]]. Passing ms directly doesn't work, and trying to convert it into a immutable map via toMap

ms.toMap[String, Set[String]]

yields

Cannot prove that (String, scala.collection.mutable.Set[String]) <:< (String, Set[String]).

Can this be solved without manually iterating over ms and inserting all entries into a new immutable map?


回答1:


It seems that the problem is mutable set. So turning into immutable sets works:

scala> (ms map { x=> (x._1,x._2.toSet) }).toMap[String, Set[String]]
res5: scala.collection.immutable.Map[String,Set[String]] = Map()

Or even better by following Daniel Sobral suggestion:

scala> (ms mapValues { _.toSet }).toMap[String, Set[String]]
res7: scala.collection.immutable.Map[String,Set[String]] = Map()



回答2:


How about using mapValues to change the Set alone?



来源:https://stackoverflow.com/questions/11386918/mutable-multimap-to-immutable-map

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