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
// 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) } } |
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 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) } } |
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.
Recommended Posts:
- Scala Map last() method with example
- Scala Map take() method with example
- Scala Map get() method with example
- Scala Map max() method with example
- Scala Map min() method with example
- Scala map contains() method with example
- Scala Iterator max() method with example
- Scala map isDefinedAt() method with example
- Scala Map exists() method with example
- Scala Map init() method with example
- Scala Iterator next() method with example
- Scala Map clone() method with example
- Scala Iterator seq() method with example
- Scala Map filterKeys() method with example
- Scala List min() method with example
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.



