cool breeze cool breeze - 1 year ago 77
Scala Question

Removing Try failures in collection using flatMap

I have a Map[String, String]

How can I simply this expression using flatMap?

val carNumbers = => Try(k.stripPrefix("car_number_").toInt)).toList.filter(_.isSuccess)

Note: I want to remove the Failure/Success wrapper and just have a List[Int].

Answer Source

It looks like you just want to convert Try to Option:

for {
  key <- carMap.keys
  t <- Try(key.stripPrefix("car_number_").toInt).toOption
} yield t

this will result Iterable and you can convert it to list with .toList method.

Also you can go with oneliner like this:

carMap.keys.flatMap(k => Try(k.stripPrefix("car_number_").toInt).toOption)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download