Kotlin List associate()
Syntax & Examples
Syntax of List.associate()
The syntax of List.associate() extension function is:
fun <T, K, V> Iterable<T>.associate( transform: (T) -> Pair<K, V> ): Map<K, V>
This associate() extension function of List returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing integers from 1 to 5. - We use the
associate()
function with a transform lambda that maps each elementit
to a Pair ofit
andit * 2
. - The resulting map contains key-value pairs where each number is associated with its double value.
- We print the map, which contains {1=2, 2=4, 3=6, 4=8, 5=10}.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5);
val map = list1.associate { it to it * 2 };
println(map);
}
Output
{1=2, 2=4, 3=6, 4=8, 5=10}
2 Example
In this example,
- We create a list named
list2
containing characters 'a' to 'c'. - We use the
associate()
function with a transform lambda that maps each characterit
to a Pair ofit
andit.toUpperCase()
. - The resulting map contains key-value pairs where each lowercase character is associated with its uppercase equivalent.
- We print the map, which contains {'a'='A', 'b'='B', 'c'='C'}.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf('a', 'b', 'c');
val map = list2.associate { it to it.toUpperCase() };
println(map);
}
Output
{a=A, b=B, c=C}
3 Example
In this example,
- We create a list named
list3
containing strings "apple", "banana", and "cherry". - We use the
associate()
function with a transform lambda that maps each stringit
to a Pair of its length andit.toUpperCase()
. - The resulting map contains key-value pairs where each string length is associated with its uppercase version.
- We print the map, which contains {5='APPLE', 6='BANANA', 6='CHERRY'}.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry");
val map = list3.associate { it.length to it.toUpperCase() };
println(map);
}
Output
{5=APPLE, 6=CHERRY}
Summary
In this Kotlin tutorial, we learned about associate() extension function of List: the syntax and few working examples with output and detailed explanation for each example.