Kotlin List associateWithTo()
Syntax & Examples


Syntax of List.associateWithTo()

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

fun <K, V, M : MutableMap<in K, in V>> Iterable<K>.associateWithTo( destination: M, valueSelector: (K) -> V ): M

This associateWithTo() extension function of List populates and returns the destination mutable map with key-value pairs for each element of the given collection, where key is the element itself and value is provided by the valueSelector function applied to that key.



✐ 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 associateWithTo function on list1 to associate each element with its square in map1.
  • The resulting map map1 contains key-value pairs where each key is an element of list1 and the value is its square.
  • 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.associateWithTo(map1) { it * it }
    println(map1)
}

Output

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

2 Example

In this example,

  • We create a list named list2 containing strings "apple", "banana", "cherry".
  • We create an empty mutable map named map2.
  • We use the associateWithTo function on list2 to associate each string with its length in map2.
  • The resulting map map2 contains key-value pairs where each key is a string from list2 and the value is its length.
  • We print map2 to standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf("apple", "banana", "cherry")
    val map2 = mutableMapOf<String, Int>()
    list2.associateWithTo(map2) { it.length }
    println(map2)
}

Output

{apple=5, banana=6, cherry=6}

3 Example

In this example,

  • We create a list named list3 containing doubles 5.5, 10.0, 15.5.
  • We create an empty mutable map named map3.
  • We use the associateWithTo function on list3 to associate each double with its integer part in map3.
  • The resulting map map3 contains key-value pairs where each key is a double from list3 and the value is its integer part.
  • We print map3 to standard output using println.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf(5.5, 10.0, 15.5)
    val map3 = mutableMapOf<Double, Int>()
    list3.associateWithTo(map3) { it.toInt() }
    println(map3)
}

Output

{5.5=5, 10.0=10, 15.5=15}

Summary

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