JAVA
List<Integer> even = new ArrayList<Integer>();
for (String num : numbersAsStrings) {
try {
int parsedInt = Integer.parseInt(num);
if (parsedInt % 2 == 0) {
ints.add(parsedInt);
}
} catch(NumberFormatException e) {
//ignore the exception (you might want to log it)
}
}
SCALA
one way to do it, using the standard tools from scala.util.control.Exception
import scala.util.control.Exception._
val numbersAsStrings = Seq("1", "2", "3", "4", "10", "N")
val ints = numbersAsStrings flatMap { catching(classOf[NumberFormatException]) opt _.toInt } filter { _ % 2 == 0 }
catching(classOf[NumberFormatException]) opt
is the main trick in this variation, as it catches the exceptions and instead returns an Option[Int]
, which is either Some(_.toInt)
if it can be parsed, or None
if it raises an exception.
Because we do not want the Option
wrapping at the end, we use flatMap
instead of map
, that gets rid of the None
values.