The easiest way to extract an option from Scala collections

Imagine what you have Map[Option[Int], String]and you want to Map[Int, String]discard the record containing Noneas the key.

Another example that should be somehow similar is to List[(Option[Int], String)]convert it to List[(Int, String)], again discarding the tuple that contains Noneas the first element.

What is the best approach?

+4
source share
1 answer

collect - your friend is here:

data definition example

val data = Map(Some(1) -> "data", None -> "")

card solution

scala> data collect { case ( Some(i), s) => (i,s) }
res4: scala.collection.immutable.Map[Int,String] = Map(1 -> data)

the same approach works for a list of tuples

scala> data.toList collect { case ( Some(i), s) => (i,s) }
res5: List[(Int, String)] = List((1,data))
+7
source

Source: https://habr.com/ru/post/1611589/


All Articles