
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin Array - map() Function
The Kotlin array map() function is used to create a list containing elements that result from applying a transformation function to each element of the original array. After the transformation, this function returns the created list containing all elements that match the transformation function.
Syntax
Following is the syntax of Kotlin array map() function −
fun <T, R> Array<out T>.map( transform: (T) -> R ): List<R>
Parameters
This function accepts a transform function as a parameter, which represent condition that we are applying in each element.
Return value
This function returns a list.
Example 1
The following is a basic example to demonstrate the use map() function −
fun main(args: Array<String>) { val numbers = arrayOf(2, 4, 6) //squaring of the elements of list println("transformed list: ${numbers.map { it * it }}") }
Output
Following is the output −
transformed list: [4, 16, 36]
Example 2
Now, let's create another example. Here, we creating a map pair of name and age. We then use map() function to display the name with age and value −
fun main(args: Array<String>) { //declaring the map pair. val peopleToAge = mapOf("Aman" to 23, "Vivek" to 24) //printing the name with age. println(peopleToAge.map { (name, age) -> "$name is $age years old" }) println(peopleToAge.map { it.value }) }
Output
Following is the output −
[Aman is 23 years old, Vivek is 24 years old] [23, 24]
Example 3
The below example creates an array and uses map function to transform the array into list containing boolean value −
fun main(args: Array<String>) { val array = arrayOf(1, 2, 3, 4, 5) val list = array.map({it%2==0}) println("True if array elements satisfy transform function, otherwise, false") println("list: $list") }
Output
Following is the output −
True if array elements satisfy transform function, otherwise, false list: [false, true, false, true, false]