scala - flatMap a list of strings to a list of integers -


given list s strings, e.g.:

val list = list("1", "2") 

i can convert them list of integers with:

list.map(_.toint) 

however, if list of strings contains non-integers, there way fillter them out in scala?

for example:

val list = list("1", "2", "output") 

using above map(_.toint) have exception:

java.lang.numberformatexception: input string: "output"

i trying using flatmap, won't compile:

:13: error: type mismatch;
found : int
required: scala.collection.gentraversableonce[?]

try good, want avoid exceptions.

list("4","4g5","77").collect{case x if x.forall(_.isdigit) => x.toint}  //res0: list[int] = list(4, 77) 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -