How to convert string array to int array in scala

18,232

Applying a function to every element of a collection is done using .map :

scala> val arr = Array("1", "12", "123")
arr: Array[String] = Array(1, 12, 123)

scala> val intArr = arr.map(_.toInt)
intArr: Array[Int] = Array(1, 12, 123)

Note that the _.toInt notation is equivalent to x => x.toInt :

scala> val intArr = arr.map(x => x.toInt)
intArr: Array[Int] = Array(1, 12, 123)

Obviously this will raise an exception if one of the element is not an integer :

scala> val arr = Array("1", "12", "123", "NaN")
arr: Array[String] = Array(1, 12, 123, NaN)

scala> val intArr = arr.map(_.toInt)
java.lang.NumberFormatException: For input string: "NaN"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:580)
  at java.lang.Integer.parseInt(Integer.java:615)
  at scala.collection.immutable.StringLike$class.toInt(StringLike.scala:272)
  ...
  ... 33 elided
Share:
18,232

Related videos on Youtube

Mohammad Gharehyazie
Author by

Mohammad Gharehyazie

PhD Candidate, Computer Scientist/Engineer. I am an R enthusiast.

Updated on June 07, 2022

Comments

  • Mohammad Gharehyazie
    Mohammad Gharehyazie about 2 years

    I am very new to Scala, and I am not sure how this is done. I have googled it with no luck. let us assume the code is:

    var arr = readLine().split(" ")
    

    Now arr is a string array. Assuming I know that the line I input is a series of numbers e.g. 1 2 3 4, I want to convert arr to an Int (or int) array.

    I know that I can convert individual elements with .toInt, but I want to convert the whole array.

    Thank you and apologies if the question is dumb.

Related