Open In App

Program to transform an array of String to an array of Int using map function in Scala

Last Updated : 06 Feb, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In Scala an array of String can be converted to an array of Int, utilizing map function. Here, the strings of the stated array will be called by the map function which has a length method in it as its argument. Then this array of strings will return an array of integers, where these integers are the length of an each string stated in an array.
Now, lets see some examples below in order to understand it in details.
Example: 1#




// Scala program to transform an array of 
// String to an array of Int using map 
// function
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an array
        val x = Array("12", "6", "888")
          
        // Applying map function and also
        // using toInt method as argument
        val y = x.map(_.toInt)
          
        // Using for loop
        for(z <-y)
          
        // Displays output
        println(z) 
      
    }
}


Output:

12
6
888

So, here the array of strings are transformed to an array of integers. And duplicate elements will also repeat.
Example: 2#




// Scala program to transform an array of 
// String to an array of Int using map 
// function
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an array where there
        // are spaces as strings
        val arr = Array("", " ", " ")
          
        // Applying map function and also
        // using length method as argument
        val m = arr.map(_.length)
          
        // Using for loop to print the 
        // results
        for(res <-m)
          
        // Displays output
        println(res) 
          
    }
}


Output:

0
1
2

Here, if there is one space in the string then the length is counted as one of there is no space then the length is zero and if there is two spaces then the length is two and so on.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads