scala None 值的过滤器映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11854433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:25:43  来源:igfitidea点击:

Filter map for values of None

scalafunctional-programminghashmapfiltering

提问by KChaloux

I've searched around a bit, but haven't found a good answer yet on how to filter out any entries into a map that have a value of None. Say I have a map like this:

我已经搜索了一些,但还没有找到关于如何将任何条目过滤到具有 None 值的地图的好答案。假设我有一张这样的地图:

val map = Map[String, Option[Int]]("one" -> Some(1), 
                                   "two" -> Some(2), 
                                   "three" -> None)

I'd like to end up returning a map with just the ("one", Some(1))and ("two", Some(2))pair. I understand that this is done with flatten when you have a list, but I'm not sure how to achieve the effect on a map without splitting it up into keys and values, and then trying to rejoin them.

我想最终返回一张只有("one", Some(1))and("two", Some(2))对的地图。我知道当你有一个列表时,这是通过 flatten 完成的,但我不确定如何在不将其拆分为键和值的情况下在地图上实现效果,然后尝试重新加入它们。

回答by Kristian Domagala

If you're filtering out Nonevalues, you might as well extract the Somevalues at the same time to end up with a Map[String,Int]:

如果您要过滤掉None值,您不妨同时提取这些Some值以得到一个Map[String,Int]

scala> map.collect { case (key, Some(value)) => (key, value) }
res0: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2)

回答by drexin

Like every collection type in the scala.collection namespace a Maphas the filtermethod defined and Optionhas the isDefinedmethod, which is truefor Someand falsefor None. You can filter out the Nonevalues by combining these two:

像在scala.collection名称空间中的每一个收集型Map具有filter定义的方法和Option具有所述isDefined方法,这是trueSomefalse进行None。您可以None通过组合这两者来过滤掉这些值:

scala> map.filter(_._2.isDefined)
res4: scala.collection.immutable.Map[String,Option[Int]] = Map(one -> Some(1), two -> Some(2))

回答by ConorR

Also map.filterKeys( map(_) != None)

map.filterKeys( map(_) != None)

or

或者

for( (k,v) <- map if( v!= None)) yield (k,v)

for( (k,v) <- map if( v!= None)) yield (k,v)

This approach provides a general filterValues method that doesn't exist on maps.
I miss such a method, because none of the alternatives is perfect.

这种方法提供了地图上不存在的通用 filterValues 方法。
我想念这样的方法,因为没有一个替代方案是完美的。

[Updated later] This is a better version that doesn't do a lookup on each entry and still reads reasonably clearly.

[稍后更新] 这是一个更好的版本,它不会对每个条目进行查找,但仍然可以合理清晰地阅读。

map.filter( {case (x,y)=> y!=None})

map.filter( {case (x,y)=> y!=None})