Scala list map() operation with examples

 182 total views,  2 views today

Welcome to the Scala series. In this tutorial, you will learn about the Scala List map() operation with examples.

Scala map() operation will transform each element of the collection to another form according to the provided function.map()  takes a function and applies the function to each element.map() returns a new collection.map() operation is mainly used to transform each element of the collection from one form to another. For e.g., transforming integer elements to string elements.

Scala map() operation is applicable to all types of Scala collection.

map() Syntax

final def map[B](f: (A) => B): List[B]

Builds a new list by applying a function to all elements of this list.

Scala List map() examples

In this map() example, we have created a list and called map() method to multiply each element with 2.

object MapTest {

  def main(args: Array[String]): Unit = {

    //create a List
    var list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)

    list.map(ele => ele * 2).foreach(println)

  }
}

Output

2
4
6
8
10
12
14
16

In the below map() example, we are converting integer elements to string elements and thus returning a list of Strings.

object Maptest {

  def main(args: Array[String]): Unit = {

    //create a List
    var list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)

    list.map(ele => ele.toString()).foreach(println)

  }
}

Output

1
2
3
4
5
6
7
8

In another map() example, we are appending a constant with each element of the list.

object Maptest {

  def main(args: Array[String]): Unit = {

    //create a List
    var list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)

    list.map(ele => "Hi-" + ele).foreach(println)

  }
}

Output

Hi-1
Hi-2
Hi-3
Hi-4
Hi-5
Hi-6
Hi-7
Hi-8

ReferencesScala map() operation

Would you like to learn more about Scala features, please check out Scala – a complete guide series. In this tutorial guide, you will find useful Scala functions that can be applied to the collection.

I hope you like this tutorial and you were able to understand the Scala list map() operation with examples.

Thanks for reading and please give us a thumb up and comment below.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

8 thoughts on “Scala list map() operation with examples

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.