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
list1containing the integers1, 2, 3, 4. - We use the
associateWithfunction onlist1to create a map where each element oflist1is a key and the square of the element is the value. - 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 = 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
list2containing strings"apple", "banana", "cherry". - We use the
associateWithfunction onlist2to create a map where each string inlist2is a key and the length of the string is the value. - 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 = list2.associateWith { 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 use the
associateWithfunction onlist3to create a map where each double inlist3is a key and its integer part is the value. - 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 = 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.