Imagine you have a Map[Option[Int], String]
and you want to have a Map[Int, String]
discarding the entry which contain None
as the key.
Another example, that should be somehow similar is List[(Option[Int], String)]
and transform it to List[(Int, String)]
, again discarding the tuple which contain None
as the first element.
What's the best approach?
collect
is your friend here:
val data = Map(Some(1) -> "data", None -> "")
scala> data collect { case ( Some(i), s) => (i,s) }
res4: scala.collection.immutable.Map[Int,String] = Map(1 -> data)
scala> data.toList collect { case ( Some(i), s) => (i,s) }
res5: List[(Int, String)] = List((1,data))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With