Whats the best way of getting a list of a field from a object?

453 Views Asked by At

So right now I have a list of a object with a Optional Field like this in scala

case class Foo(
                   id: String,
                   description: String,
                   OptionalTag: Option[String],
) 

What I want is to iterate through the list of objects and only get the Optional Tags if they exists, my current approach is this

     Tags = listOfFoos.map(foo =>
        if (foo.OptionalTag.isDefined) {
          foo.OptionalTag.get
        } else {
          ""
        }
      ).filter(_ != "" -> "")

However Im sure theres a better way to do this then go over the entire list twice but I can not figure it out.

1

There are 1 best solutions below

0
Tim On BEST ANSWER

For the specific problem you mention, flatMap is the best solution:

listOfFoos.flatMap(_.OptionalTag)

If you want to do more complex processing, collect is the best choice because it can do the job of both filter and map:

listOfFoos.collect{ case (_, _, Some(tag)) => "Tag is " + tag }