KChaloux KChaloux - 2 months ago 10x
Scala Question

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))
("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 every collection type in the scala.collection namespace a Map has the filter method defined and Optionhas the isDefined method, which is true for Some and false for None. You can filter out the Nonevalues by combining these two:

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