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
Post a Comment