可变MultiMap到不可变地图 [英] Mutable MultiMap to immutable Map
本文介绍了可变MultiMap到不可变地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建一个 MultiMap
val ms =
new collection.mutable.HashMap[String, collection.mutable.Set[String]]()
with collection.mutable.MultiMap[String, String]
在填充条目之后,必须将其传递给一个需要 Map [String,Set [String]]
。通过 ms
直接不起作用,并尝试通过 toMap
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]]
Cannot prove that (String, scala.collection.mutable.Set[String]) <:< (String, Set[String]).
可以解决这个问题,而无需手动迭代 ms
并将所有条目插入到新的不可变地图中?
Can this be solved without manually iterating over ms
and inserting all entries into a new immutable map?
推荐答案
似乎问题是可变的设置。所以变成不可变的集合起作用:
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()
或者更好的是遵循Daniel Sobral的建议:
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()
这篇关于可变MultiMap到不可变地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文