将 Map[K, Option[V]] 转换为 Map[K,V] 的更好方法
我有一些代码生成一个 Map
,其中值是 Option
类型,我当然想要一个仅包含真实值的地图。
所以我需要对其进行转换,而我在代码中提出的内容是
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
}
有效的,但看起来不优雅。我怀疑收藏库中缺少一些与此相关的内容。
是否有内置的东西,或者更惯用的方法来实现这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是弗兰扎在后面一个问题中的回答,但值得在这里重新发布。
It's franza's answer from a later question, but it deserves a re-post here.