.map()
Published Oct 15, 2024
Contribute to Docs
In Kotlin, the .map()
method transforms elements in a collection (Array, List, or Set) using the provided logic. It does not modify the original collection, ensuring data permanence, which can be useful in scenarios where the original data must remain unchanged.
Syntax
fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R>
Or alternatively:
fun <T, R> Array<T>.map(transform: (T) -> R): List<R>
T
: The type of the elements in the original collection (or array).R
: The type of the elements in the resulting list after transformation.transform
: A function that takes an element of typeT
and returns a transformed value of typeR
.
It returns a List<R>
containing the transformed elements.
Example
The following example uses the .map()
function:
fun main() {// Initialize an Array of numbers.val numbers = arrayOf(4, 12, 14, 17, 8)// Use .map() to multiply each element by 2val doubledNumbers = numbers.map { it * 2 } // Transforms each element by multiplying it by 2// Print the transformed arrayprintln(doubledNumbers)}
The code above generates the following output:
[8, 24, 28, 34, 16]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Kotlin
Learn Kotlin, the expressive, open-source programming language developed by JetBrains.Beginner Friendly9 hours