Kotlin List associateTo()
Syntax & Examples


Syntax of List.associateTo()

The syntax of List.associateTo() extension function is:

fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateTo( destination: M, transform: (T) -> Pair<K, V> ): M

This associateTo() extension function of List populates and returns the destination mutable map with key-value pairs provided by transform function applied to each element of the given collection.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing strings "apple", "banana", and "cherry".
  • We create an empty mutable map named map with keys as integers and values as strings.
  • We use the associateTo function to populate map with key-value pairs where the key is the length of the string and the value is the string itself.
  • The resulting map map contains entries like {5: 'apple', 6: 'banana', 6: 'cherry'}.
  • We print the map using println(map).

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "cherry");
    val map = mutableMapOf<Int, String>();
    list1.associateTo(map) { Pair(it.length, it) };
    println(map);
}

Output

{5=apple, 6=cherry}

2 Example

In this example,

  • We create a list named list1 containing integers 10, 20, and 30.
  • We create an empty mutable map named map with keys and values as integers.
  • We use the associateTo function to populate map with key-value pairs where the key is the integer itself and the value is double the integer.
  • The resulting map map contains entries like {10: 20, 20: 40, 30: 60}.
  • We print the map using println(map).

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val map = mutableMapOf<Int, Int>();
    list1.associateTo(map) { Pair(it, it * 2) };
    println(map);
}

Output

{10: 20, 20: 40, 30: 60}

3 Example

In this example,

  • We define a data class Person with properties name and age.
  • We create a list named list1 containing instances of Person with names "Alice" and "Bob" along with their ages.
  • We create an empty mutable map named map with keys as strings and values as integers.
  • We use the associateTo function to populate map with key-value pairs where the key is the name of the person and the value is their age.
  • The resulting map map contains entries like {'Alice': 30, 'Bob': 25}.
  • We print the map using println(map).

Kotlin Program

fun main(args: Array<String>) {
    data class Person(val name: String, val age: Int)
    val list1 = listOf(Person("Alice", 30), Person("Bob", 25));
    val map = mutableMapOf<String, Int>();
    list1.associateTo(map) { Pair(it.name, it.age) };
    println(map);
}

Output

{Alice: 30, Bob: 25}

Summary

In this Kotlin tutorial, we learned about associateTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.