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 ): MThis 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
list1containing the integers1, 2, 3, 4. - We create an empty mutable map named
map1. - We use the
associateWithTofunction onlist1to associate each element with its square inmap1. - The resulting map
map1contains key-value pairs where each key is an element oflist1and the value is its square. - We print
map1to standard output usingprintln.
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
list2containing strings"apple", "banana", "cherry". - We create an empty mutable map named
map2. - We use the
associateWithTofunction onlist2to associate each string with its length inmap2. - The resulting map
map2contains key-value pairs where each key is a string fromlist2and the value is its length. - We print
map2to standard output usingprintln.
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
list3containing doubles5.5, 10.0, 15.5. - We create an empty mutable map named
map3. - We use the
associateWithTofunction onlist3to associate each double with its integer part inmap3. - The resulting map
map3contains key-value pairs where each key is a double fromlist3and the value is its integer part. - We print
map3to standard output usingprintln.
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.