map() Method in Scala

Scala | map() Method: Here, we will be going to learn about map() method in Scala with syntaxes and examples based on working.
Submitted by Shivang Yadav, on November 23, 2020

map() method in Scala is a built-in function in Scala that is used for the transformation of the collection in Scala.

The map() method is defined for all collection object methods in Scala. Also, the method takes a conversion function which is used while converting the collections. For the map() function the type of source and destination collections are the same.

Syntax:

collection.map(convFunc)

Parameters:

  • convFunc - It is a conversion function that is used for the conversion of elements of the collection.

Return value:

The function returns a new collection of the same type as the initial function.

Examples:

Here, we will see the use of different types of methods as parameters to map() method.

Example 1: using an anonymous function as a parameter to map() method

//Program to illustrate the working of map() function

object MyObject {
    def main(args: Array[String]) {
        val coll1 = List(5, 2, 9, 7, 1, 19) 
        
        println("Initial collection: "+coll1)
        
        val coll2 = coll1.map(x =>  x + 5) 
        
        println("Mapped collection with function to add 5: "+coll2)
    }
}

Output:

Initial collection: List(5, 2, 9, 7, 1, 19)
Mapped collection with function to add 5: List(10, 7, 14, 12, 6, 24)

Explanation:

Here, we have created a collection coll1 which is a list. Then we have used the map() method in which we have passed an anonymous function to add 5 to the element. And then print the new list created.

Example 2: using a user-defined function as a parameter to map() method

// Program to illustrate the working of map() function

object MyObject {
    def convFunc(x:Int) : Int = { 
       2*x;
    }

    def main(args: Array[String]) {
        val coll1 = Array(1, 3, 4, 6, 7, 9) 
        
        print("Initial collection: ")
        for(i <-  1 to coll1.length - 1)
            print("\t"+ coll1(i));
        
        val coll2 = coll1.map(convFunc) 
        
        print("\nMapped collection with function to multiply by 2: ")
        for(i <-  1 to coll1.length - 1)
            print("\t"+ coll2(i));
    }
}

Output:

Initial collection: 	3	4	6	7	9
Mapped collection with function to multiply by 2: 	6	8	12	14	18

Explanation:

Here, we have created a collection coll1 which is an array. Then we have transformed the collection using map() method in which we have passed a user-defined to multiply the value by 2. And then print the new array created.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.