Arturs Vancans Arturs Vancans - 1 year ago 56
Scala Question

Filtering a list based on Optional property in Scala

Imagine I have the following list where

second arg is optional

List(Tuple("FullName", Some(1)), Tuple("FullName", None))

What is the cleanest approach to get the following result?

List(Tuple("FullName", 1))

I could try

list.filter(_._2.isDefined).map((_._1, _._2.get))

I need to filter out all Tuples where the 2nd argument is
and then change the tuple type to contain a defined
and not an

I was wondering if there is a prettier way of doing this?

m-z m-z
Answer Source

Yes, use collect and pattern matching.

val list = List(("FullName", Some(1)), ("FullName", None))

scala> list collect { case (name, Some(i)) => (name, i) }
res0: List[(String, Int)] = List((FullName,1))

collect allows you to provide a partial function that will keep any values that are defined within the partial function, and discard any that are not.