I have a map:
Map(\"key1\" -> Some(\"value1\"), \"key2\" -> None, \"key3\" -> Some(\"value3\"))
I want to remove all None
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
Using partition over the map, like this,
val (flattened,_) = map.partition(_._2.isDefined)
You can use for-comprehension + pattern-matching:
for((k, Some(v)) <- yourMap) yield k -> v
My take using for comprehensions:
val m = Map("key1" -> Some("value1"), "key2" -> None, "key3" -> Some("value3"))
for( (key,value) <- m if(value.isDefined)) yield (key,value.get)