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