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,
- Take a list of integers.
- Define a transformation to return the square of the number.
- Call map() function on this list, and pass transformation as argument the function.
- 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,
- Take a list of strings.
- Define a transform that returns the length for a given string.
- Call map() function on this list, and pass transformation as argument the function.
- 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]