Kotlin List map()
Syntax & Examples
Syntax of List.map()
The syntax of List.map() extension function is:
fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R>
This map() extension function of List returns a list containing the results of applying the given transform function to each element in the original collection.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list
containing elements1, 2, 3, 4, 5
. - We use the
map()
function to multiply each element by 2. - The transformed list,
result
, is printed to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
val result = list.map { it * 2 }
println("Mapped list: \$result")
}
Output
Mapped list: [2, 4, 6, 8, 10]
2 Example
In this example,
- We create a list of characters named
list
containing elements'a', 'b', 'c'
. - We use the
map()
function to convert each character to uppercase. - The transformed list,
result
, is printed to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c')
val result = list.map { it.toUpperCase() }
println("Mapped list: \$result")
}
Output
Mapped list: [A, B, C]
3 Example
In this example,
- We create a list of strings named
list
containing elements"apple", "banana", "cherry"
. - We use the
map()
function to get the length of each string. - The transformed list,
result
, is printed to standard output using println statement.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry")
val result = list.map { it.length }
println("Mapped list: \$result")
}
Output
Mapped list: [5, 6, 6]
Summary
In this Kotlin tutorial, we learned about map() extension function of List: the syntax and few working examples with output and detailed explanation for each example.