Kotlin List associateByTo()
Syntax & Examples


Syntax of List.associateByTo()

There are 2 variations for the syntax of List.associateByTo() extension function. They are:

1.
fun <T, K, M : MutableMap<in K, in T>> Iterable<T>.associateByTo( destination: M, keySelector: (T) -> K ): M

This extension function populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given collection and value is the element itself.

2.
fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateByTo( destination: M, keySelector: (T) -> K, valueTransform: (T) -> V ): M

This extension function populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function applied to elements of the given collection.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the integers 1, 2, 3, 4.
  • We create an empty mutable map named map1.
  • We use the associateByTo function on list1 to associate each element with itself as the key in map1.
  • The resulting map map1 contains key-value pairs where each element of list1 is both the key and value.
  • We print map1 to standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4)
    val map1 = mutableMapOf<Int, Int>()
    list1.associateByTo(map1, { it })
    println(map1)
}

Output

{1=1, 2=2, 3=3, 4=4}

2 Example

In this example,

  • We define a data class Person with properties name and age.
  • We create a list named people containing instances of Person.
  • We create an empty mutable map named map2.
  • We use the associateByTo function on people to associate each person's name with their age in map2.
  • The resulting map map2 contains key-value pairs where each person's name is the key and their age is the value.
  • We print map2 to standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    data class Person(val name: String, val age: Int)
    val people = listOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
    val map2 = mutableMapOf<String, Int>()
    people.associateByTo(map2, { it.name }, { it.age })
    println(map2)
}

Output

{Alice=30, Bob=25, Charlie=35}

Summary

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