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 integers1, 2, 3, 4
. - We use the
associateWith
function onlist1
to create a map where each element oflist1
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 oflist1
and the value is its square. - We print
map1
to 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
list2
containing strings"apple", "banana", "cherry"
. - We use the
associateWith
function onlist2
to create a map where each string inlist2
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 fromlist2
and the value is its length. - We print
map2
to 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
list3
containing doubles5.5, 10.0, 15.5
. - We use the
associateWith
function onlist3
to create a map where each double inlist3
is a key and its integer part is the value. - The resulting map
map3
contains key-value pairs where each key is a double fromlist3
and the value is its integer part. - We print
map3
to 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.