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

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#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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) 
      
    }
}

chevron_right


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#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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) 
          
    }
}

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.