Scala Tutorial - Learn How To Use Map Function With Examples

By Nadim Bahadoor | Last updated: March 16, 2018 at 14:36 pm

Overview

In this tutorial, we will learn how to use the map function with examples on collection data structures in Scala. The map function is applicable to both Scala's Mutable and Immutable collection data structures.

 

The map method takes a predicate function and applies it to every element in the collection. It creates a new collection with the result of the predicate function applied to each and every element of the collection.

 

As per the Scala documentation, the definition of the map method is as follows:

def map[B](f: (A) ⇒ B): Traversable[B]

 

The map method is a member of the TraverableLike trait but there are specialized versions of the map methods for given collection types.

Steps

1. How to initialize a Sequence of donuts

The code below shows how to initialize a Sequence of donut elements where each element in the Sequence is of type String.


println("Step 1: How to initialize a Sequence of donuts")
val donuts1: Seq[String] = Seq("Plain", "Strawberry", "Glazed")
println(s"Elements of donuts1 = $donuts1")

 

You should see the following output when you run your Scala application in IntelliJ:


Step 1: How to initialize a Sequence of donuts
Elements of donuts1 = List(Plain, Strawberry, Glazed)

 

2. How to append the word Donut to each element using the map function

The code below shows how to use the map method to append the String Donut to each donut element in the Sequence.


println("\nStep 2: How to append the word Donut to each element using the map function")
val donuts2: Seq[String] = donuts1.map(_ + " Donut")
println(s"Elements of donuts2 = $donuts2")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: How to append the word Donut to each element using the map function
Elements of donuts2 = List(Plain Donut, Strawberry Donut, Glazed Donut)

NOTE:

  • We've used the wildcard operator inside the map method.

3. How to create a donut sequence with one None element

The code below shows how another donut Sequence but which also contains a None element.


println("\nStep 3: How to create a donut sequence with one None element")
val donuts3: Seq[AnyRef] = Seq("Plain", "Strawberry", None)
donuts3.foreach(println(_))

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to create a donut sequence with one None element
Plain
Strawberry
None

 

4. How to filter out the None element using map function

The code below shows how to use the map method along with pattern matching to filter out the None element in the Donut sequence.


println("\nStep 4: How to filter out the None element using map function")
val donuts4: Seq[String] = donuts3.map {
 case donut: String => donut + " Donut"
 case None => "Unknown Donut"
}
println(s"Elements of donuts4 = $donuts4")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to filter out the None element using map function
Elements of donuts4 = List(Plain Donut, Strawberry Donut, Unknown Donut)

 

5. How to define couple of functions which returns an Option of type String

The code below shows how to define two function both of which return an Option of type String which represent either a Donut or None.


println("\nStep 5: How to define couple of functions which returns an Option of type String")
def favoriteDonut: Option[String] = Some("Glazed Donut")

def leastFavoriteDonut: Option[String] = None

6. How to use map function to filter out None values

The code below shows how to use the map method to filter out None values from function return values.


println("\nStep 6: How to use map function to filter out None values")
favoriteDonut.map(donut => println(s"Favorite donut = $donut"))
leastFavoriteDonut.map(donut=> println(s"Least favorite donut = $donut"))

You should see the following output when you run your Scala application in IntelliJ:


Step 6: How to use map function to filter out None values
Favorite donut = Glazed Donut

NOTE:

  • When leastFavoriteDonut function is called, nothing is printed because the map method has already filtered out None values.

This concludes our tutorial on Learn How To Use Map Function With Examples and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to initialize a Sequence of donuts
  • How to append the word Donut to each element using the map function
  • How to create a donut sequence with one None element
  • How to filter out the None element using map function
  • How to define couple of functions which returns an Option of type String
  • How to use map function to filter out None values

Tip

  • Review the tutorials on Mutable and Immutable collection data structures in Scala.

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to use max function.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: