The map function

The map function allows you to apply an algorithm to a collection all-together and obtain the results as a resultant set. It's helpful in making your code well-organized and writing loops (though it'll use loop internally, you're freed from writing those boilerplate codes).

The map function receives all the elements of the collection as each iteration and should return the computed resultant item that should be placed in the resultant list in place of the passed item.

Go through the following example:

fun main(args: Array<String>) { 
    val list = listOf<Int>(1,2,3,4,5,6,7,8,9,10) 
    val modifiedList = list.map { it*2 } 
 
    println("modifiedList -> $modifiedList") 
} 

So, we had a list of Int, we needed to multiply each item from the list value with 2, and we did it with ease with just a single line of code—list.map { it*2 }, which would normally take us two or three lines more of boilerplate. Insane, isn't it?

The following is the output of the program:

As expected, the map function applied the provided lambda to each of the elements of the list and returned the resultant list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.45.80