Kotlin List associateBy()
Syntax & Examples
Syntax of List.associateBy()
There are 2 variations for the syntax of List.associateBy() extension function. They are:
1.
fun <T, K> Iterable<T>.associateBy( keySelector: (T) -> K ): Map<K, T>This extension function returns a Map containing the elements from the given collection indexed by the key returned from keySelector function applied to each element.
2.
fun <T, K, V> Iterable<T>.associateBy( keySelector: (T) -> K, valueTransform: (T) -> V ): Map<K, V>This extension function returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing strings "apple", "banana", and "cherry". - We use the
associateByfunction withkeySelectoras{ it.first() }to index elements by their first character. - The resulting map
mapindexes elements like{'a': 'apple', 'b': 'banana', 'c': 'cherry'}. - We print the map using
println(map).
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry");
val map = list1.associateBy { it.first() };
println(map);
}Output
{a=apple, b=banana, c=cherry}2 Example
In this example,
- We define a data class
Personwithnameandageproperties. - We create a list named
peoplecontaining instances ofPerson. - We use the
associateByfunction withkeySelectorasPerson::nameto index elements by their names. - The resulting map
mapindexes elements by names, e.g.,{'Alice': Person('Alice', 25), 'Bob': Person('Bob', 30), 'Charlie': Person('Charlie', 35)}. - We print the map using
println(map).
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val people = listOf(Person("Alice", 25), Person("Bob", 30), Person("Charlie", 35));
val map = people.associateBy(Person::name);
println(map);
}Output
{Alice=Person(name=Alice, age=25), Bob=Person(name=Bob, age=30), Charlie=Person(name=Charlie, age=35)}3 Example
In this example,
- We create a list named
list1containing integers from 1 to 5. - We use the
associateByfunction withkeySelectoras{ it * 2 }to index elements by their double values. - We also provide a
valueTransformfunction to prepend the string "Number " to each element. - The resulting map
mapindexes elements like{2: 'Number 1', 4: 'Number 2', 6: 'Number 3', 8: 'Number 4', 10: 'Number 5'}. - We print the map using
println(map).
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5);
val map = list1.associateBy({ it * 2 }, { "Number " + it.toString() });
println(map);
}Output
{2=Number 1, 4=Number 2, 6=Number 3, 8=Number 4, 10=Number 5}Summary
In this Kotlin tutorial, we learned about associateBy() extension function of List: the syntax and few working examples with output and detailed explanation for each example.