Scala | map() method

A collection in Scala is a data structure which holds a group of objects. Examples of collections include Arrays, Lists, etc. We can apply some transformations to these collections using several methods. One such widely used method offered by Scala is map().
Important points about map() method:

  • map() is a higher order function.
  • Every collection object has the map() method.
  • map() takes some function as a parameter.
  • map() applies the function to every element of the source collection.
  • map() returns a new collection of the same type as the source collection.

Syntax:

collection = (e1, e2, e3, ...)

//func is some function
collection.map(func)

//returns collection(func(e1), func(e2), func(e3), ...)

Example 1: Using user-defined function

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to
// transform a collection
// using map()
  
//Creating object
object GfG
{
  
    // square of an integer
    def square(a:Int):Int
    =
    {
        a*a
    }
  
    // Main method
    def main(args:Array[String])
    {
        // source collection
        val collection = List(1, 3, 2, 5, 4, 7, 6)
      
        // transformed collection
        val new_collection = collection.map(square)
  
        println(new_collection)
  
    }
  
}

chevron_right


Output:

List(1, 9, 4, 25, 16, 49, 36)

In the above example, we are passing a user-defined function square as a parameter to the map() method. A new collection is created which contains squares of elements of the original collection. The source collection remains unaffected.

Example 2: Using anonymous function

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to
// transform a collection
// using map()
  
//Creating object
object GfG
{
      
    // Main method
    def main(args:Array[String])
    {
        // source collection
        val collection = List(1, 3, 2, 5, 4, 7, 6)
  
        // transformed collection
        val new_collection = collection.map(x => x * x )
  
        println(new_collection)
    }
}

chevron_right


Output:

List(1, 9, 4, 25, 16, 49, 36)

In the above example, an anonymous function is passed as a parameter to the map() method instead of defining a whole function for square operation. This approach reduces the code size.



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.