0
0
Kotlinprogramming~5 mins

Map transformation in Kotlin

Choose your learning style9 modes available
Introduction

Map transformation helps you change each item in a list or collection into something new. It is like turning raw ingredients into a finished dish.

You want to change a list of numbers into their squares.
You have a list of names and want to make them all uppercase.
You want to convert a list of strings into their lengths.
You need to add a fixed value to every number in a list.
Syntax
Kotlin
val newList = oldList.map { item -> transformation }

The map function creates a new list with transformed items.

The item inside the curly braces is each element from the original list.

Examples
This example squares each number in the list.
Kotlin
val numbers = listOf(1, 2, 3)
val squares = numbers.map { it * it }
This example changes all names to uppercase letters.
Kotlin
val names = listOf("alice", "bob")
val upperNames = names.map { it.uppercase() }
This example finds the length of each word.
Kotlin
val words = listOf("cat", "dog")
val lengths = words.map { it.length }
Sample Program

This program adds 5 to each price in the list and prints both the original and new lists.

Kotlin
fun main() {
    val prices = listOf(10, 20, 30)
    val increasedPrices = prices.map { it + 5 }
    println("Original prices: $prices")
    println("Increased prices: $increasedPrices")
}
OutputSuccess
Important Notes

The map function does not change the original list; it returns a new list.

You can use it as a shortcut for the single parameter inside the lambda.

Summary

Map transformation changes each item in a list to a new form.

It returns a new list without changing the original.

Use it when you want to apply the same change to every item.