Kotlin List associateByTo()
Syntax & Examples
Syntax of List.associateByTo()
There are 2 variations for the syntax of List.associateByTo() extension function. They are:
fun <T, K, M : MutableMap<in K, in T>> Iterable<T>.associateByTo( destination: M, keySelector: (T) -> K ): MThis 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.
fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.associateByTo( destination: M, keySelector: (T) -> K, valueTransform: (T) -> V ): MThis 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
list1containing the integers1, 2, 3, 4. - We create an empty mutable map named
map1. - We use the
associateByTofunction onlist1to associate each element with itself as the key inmap1. - The resulting map
map1contains key-value pairs where each element oflist1is both the key and value. - 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.associateByTo(map1, { it })
println(map1)
}Output
{1=1, 2=2, 3=3, 4=4}2 Example
In this example,
- We define a data class
Personwith propertiesnameandage. - We create a list named
peoplecontaining instances ofPerson. - We create an empty mutable map named
map2. - We use the
associateByTofunction onpeopleto associate each person's name with their age inmap2. - The resulting map
map2contains key-value pairs where each person's name is the key and their age is the value. - We print
map2to standard output usingprintln.
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.