Filter map for values of None

Viewed 42481

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:

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.

3 Answers

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

or

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.

[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})

Related