Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter map for values of None

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.

like image 611
KChaloux Avatar asked Aug 07 '12 21:08

KChaloux


1 Answers

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

scala> map.collect { case (key, Some(value)) => (key, value) } res0: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2) 
like image 146
Kristian Domagala Avatar answered Oct 04 '22 15:10

Kristian Domagala