Arturs Vancans
Arturs Vancans

Reputation: 4640

Filtering a list based on Optional property in Scala

Imagine I have the following list where Tuple 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 None and then change the tuple type to contain a defined integer and not an option.

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

Upvotes: 1

Views: 299

Answers (2)

Ori Popowski
Ori Popowski

Reputation: 10662

Another possibility that doesn't use get() might be

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

list.filter(_._2.isDefined).unzip match {
  case (k, v) => k zip v.flatten
}

Upvotes: 0

Michael Zajac
Michael Zajac

Reputation: 55569

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.

Upvotes: 5

Related Questions