Kotlin List associateWith()
Syntax & Examples


Syntax of List.associateWith()

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

fun <K, V> Iterable<K>.associateWith( valueSelector: (K) -> V ): Map<K, V>

This associateWith() extension function of List returns a Map where keys are elements from the given collection and values are produced by the valueSelector function applied to each element.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the integers 1, 2, 3, 4.
  • We use the associateWith function on list1 to create a map where each element of list1 is a key and the square of the element is the value.
  • 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 = list1.associateWith { 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 use the associateWith function on list2 to create a map where each string in list2 is a key and the length of the string is the value.
  • 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 = list2.associateWith { 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 use the associateWith function on list3 to create a map where each double in list3 is a key and its integer part is the value.
  • 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 = list3.associateWith { it.toInt() }
    println(map3)
}

Output

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

Summary

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