1. Overview
In this tutorial, we’ll learn how to convert a List of String into a List of Int using only the standard library.
2. Using the String.toInt Method
Let’s assume all elements in the List of String are convertible into Int, and ignore the case where an element may be random text, for simplicity.
The simplest approach is by using the String.toInt() method, available in the Scala standard library:
scala> val lst = List("1", "2", "3")
lst: List[String] = List(1, 2, 3)
scala> lst.map(s => s.toInt)
res0: List[Int] = List(1, 2, 3)
Which can be further simplified:
scala> lst.map(_.toInt)
res1: List[Int] = List(1, 2, 3)
This makes for a clean approach. We just need to map each element using the handy method.
3. Dealing with Non-Numeric Strings
A common issue we may face on such operations is that the given List may contain some strings that aren’t convertible into an Int:
scala> val lst = List("1", "abc", "2")
lst: List[String] = List(1, abc, 2)
scala> lst.map(_.toInt)
java.lang.NumberFormatException: For input string: "abc"
In such cases, we’d get an exception when converting that String. We can either fail the conversion of all elements, as we have in the previous example, or we can just skip such elements, operating on only the ones that are convertible to Int. Let’s use the scala.util.Try here:
scala> import scala.util.Try
import scala.util.Try
scala> lst.map(s => Try(s.toInt))
res10: List[scala.util.Try[Int]] = List(Success(1), Failure(java.lang.NumberFormatException: For input string: "abc"), Success(2))
Now that we captured the result of converting each element, we can discard the failures by converting them into an Option, and flattening them:
scala> lst.map(s => Try(s.toInt)).map(_.toOption)
res11: List[Option[Int]] = List(Some(1), None, Some(2))
scala> lst.map(s => Try(s.toInt)).map(_.toOption).flatten
res12: List[Int] = List(1, 2)
This can be further simplified by using the .flatMap() method:
scala> lst.map(s => Try(s.toInt)).flatMap(_.toOption)
res13: List[Int] = List(1, 2)
This will ensure we extract all convertible Strings as Int while ignoring the remainder elements.
4. Conclusion
In this article, we learned how to convert a List of String into a List of Int using the Scala standard library by mapping each element with the handy String.toInt() method. We also covered how to ignore elements that aren’t convertible into Int.