更好的将地图[K,选项[V]]转换为地图[K,V] [英] Better way of converting a Map[K, Option[V]] to a Map[K,V]
本文介绍了更好的将地图[K,选项[V]]转换为地图[K,V]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码生成 Map
,其中值是 Option
类型,我当然想要一个仅包含真实值的地图。
I have some code that is producing a Map
where the values are Option
types, and I really of course want a map containing only the real values.
所以我需要转换这个,我在代码中提出的是
So I need to convert this, and what I've come up with in code is
def toMap[K,V](input: Map[K, Option[V]]): Map[K, V] = {
var result: Map[K, V] = Map()
input.foreach({
s: Tuple2[K, Option[V]] => {
s match {
case (key, Some(value)) => {
result += ((key, value))
}
case _ => {
// Don't add the None values
}
}
}
})
result
}
这是工作,但似乎不起眼。我怀疑这里有一些内置于我缺少的集合库。
which works, but seems inelegant. I suspect there's something for this built into the collections library that I'm missing.
有什么内置的,或者更成熟的方式来完成这个? >
Is there something built in, or a more idiomatic way to accomplish this?
推荐答案
input.collect{case (k, Some(v)) => (k,v)}
这篇关于更好的将地图[K,选项[V]]转换为地图[K,V]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文