Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Remove none elements from map and flatten

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?

like image 940
Felix Avatar asked Jun 19 '13 08:06

Felix


4 Answers

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

like image 115
om-nom-nom Avatar answered Oct 22 '22 00:10

om-nom-nom


You can use for-comprehension + pattern-matching:

for((k, Some(v)) <- yourMap) yield k -> v
like image 27
dk14 Avatar answered Oct 21 '22 22:10

dk14


Using partition over the map, like this,

val (flattened,_) = map.partition(_._2.isDefined)
like image 4
elm Avatar answered Oct 21 '22 22:10

elm


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)
like image 1
gnf Avatar answered Oct 21 '22 23:10

gnf