Kotlin List - map() Function



The Kotlin List map() function is used to convert elements of a list into another list. It applies the given lambda function to transform each element of the original collection and return them into a newly created list.

There are the following use cases of the map() function:

  • Transform the List
  • Extract properties form object
  • Mapping to different data types
  • Combining data from multiple collection

Syntax

Following is the syntax of Kotlin list map() function −

val result = collection.map { transformFunction(it) }

Parameters

This function accepts lambda function to define a transformation logic.

Return value

This function returns a list containing the results of applying the given transform function.

Example 1

Let's see a basic example of the map() function, which return a list containing square of each element −

fun main(args: Array<String>) {
   val numbers = listOf(2, 3, 4)
   println(numbers.map { it * it })
}

Output

Following is the output −

[1, 4, 9]

Example 2: Chaining with Other Function

In the following example, we filter the even element in the list and use the map function to calculate the square of the even element −

fun main(args: Array<String>) {
   val numbers = listOf(1, 2, 3, 4, 5)
   val square = numbers.filter { it % 2 == 0 }.map { it * it }
   println(square)
}

Output

Following is the output −

[4, 16]

Example 3: Convert Words to their lengths

This is another example of map() function to convert the words of a list by their length and filter out words with length less than 6 −

fun main(args: Array<String>) {
   val words = listOf("Kotlin", "Java", "Swift", "Python", "JavaScript")

   val longWordsLengths = words.map { it.length }.filter { it >= 6 }

   println(longWordsLengths)
}

Output

Following is the output −

[6, 6, 10]
kotlin_lists.htm
Advertisements