Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to extract Option from Scala collections

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?

like image 843
pedrorijo91 Avatar asked Mar 15 '23 11:03

pedrorijo91


1 Answers

collect is your friend here:

example data definition

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

solution for Map

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))
like image 154
Andreas Neumann Avatar answered Mar 26 '23 12:03

Andreas Neumann