0
0
Kotlinprogramming~5 mins

Associate for map creation in Kotlin

Choose your learning style9 modes available
Introduction

We use associate to quickly turn a list into a map. It helps organize data by linking keys to values.

When you have a list of names and want to create a map of name to length.
When you want to convert a list of objects into a map using one property as the key.
When you need to group data by a unique identifier from a list.
When you want to quickly look up values by keys instead of searching a list.
Syntax
Kotlin
val map = list.associate { element -> key to value }

The associate function takes a lambda that returns a pair (key to value).

Each element in the list becomes one entry in the map.

Examples
This creates a map where each name is a key and its length is the value.
Kotlin
val names = listOf("Anna", "Bob", "Cody")
val map = names.associate { it to it.length }
This creates a map of number to its square.
Kotlin
val numbers = listOf(1, 2, 3)
val map = numbers.associate { it to it * it }
Sample Program

This program creates a map from fruit names to their lengths and prints it.

Kotlin
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    val fruitMap = fruits.associate { fruit -> fruit to fruit.length }
    println(fruitMap)
}
OutputSuccess
Important Notes

If keys are not unique, the last one wins in the map.

You can use associateBy if you only want keys from elements.

Summary

associate turns a list into a map by pairing keys and values.

Use it to organize data for quick lookup.

Keys must be unique; otherwise, later entries overwrite earlier ones.