cool breeze cool breeze - 1 month ago 13
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 = carMap.keys.map(k => 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

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)
Comments