Scala: Remove none elements from map and flatten

Felix picture Felix · Jun 19, 2013 · Viewed 11k times · Source

I have a map:

Map("key1" -> Some("value1"), "key2" -> None, "key3" -> Some("value3"))

I want to remove all None elements and flatten the map. What is the easiest way to accomplish that? I only found this way:

Map("key1" -> Some("value1"), "key2" -> None, "key3" -> Some("value3")).filter(_._2.nonEmpty).map(item => (item._1 -> item._2.getOrElse(Nil)))

The result is:

Map(key1 -> value1, key3 -> value3)

Do you know a better way?

Answer

om-nom-nom picture om-nom-nom · Jun 19, 2013

My take using pattern matching is:

Map("key1" -> Some("value1"), "key2" -> None, "key3" -> Some("value3")).collect {
  case (key, Some(value)) => key -> value
}
// Map(key1 -> value1, key3 -> value3)

Collect acts like combined map + filter