Kotlin List.map() – Examples

Kotlin List.map()

The Kotlin List.map() function returns a list containing the results of applying the given transform function to each element in the original list.

Syntax

List.map(transform)

Example 1

In this example,

  1. Take a list of integers.
  2. Define a transformation to return the square of the number.
  3. Call map() function on this list, and pass transformation as argument the function.
  4. map() returns a list. Print this returned list.

Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4, 5, 6)
    val transform: (Int) -> Int = {it*it}
    val result = list1.map( transform )
    print(result)
}

The transform take an Int and returns an Int. And performs the transformation from it to it * it.

Output

[1, 4, 9, 16, 25, 36]

Example 2

In this example,

  1. Take a list of strings.
  2. Define a transform that returns the length for a given string.
  3. Call map() function on this list, and pass transformation as argument the function.
  4. The returned list consists of lengths of strings in input list.

Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "google")
    val transform: (String) -> Int = {it.length}
    val result = list1.map( transform )
    print(result)
}

Output

[5, 6]