Kotlin List groupBy() Function
The List groupBy() function in Kotlin is used to group elements of a list based on a key returned by the provided selector function.
In this tutorial, we shall learn the syntax of List groupBy() function, and its usage, with the help of example programs.
Syntax
The syntax of List groupBy() function is
fun <T, K> Iterable<T>.groupBy(
keySelector: (T) -> K
): Map<K, List<T>>
where
Parameter | Description |
---|---|
keySelector | A function that maps elements to keys based on which the grouping is done. |
The List groupBy() function returns a map where each key is associated with a list of elements having that key.
The other variation of the groupBy() function is
fun <T, K> Iterable<T>.groupBy(
keySelector: (T) -> K,
valueTransform: (T) -> V
): Map<K, List<V>>
where
Parameter | Description |
---|---|
keySelector | A function that maps elements to keys based on which the grouping is done. |
valueTransform | This function is applied to each element of the original collection, and then grouped. |
Example 1: Grouping Integers by Even or Odd
In this example, we’ll use List groupBy() function to group a list of integers into two groups: even and odd numbers.
Kotlin Program
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
val groupedByEvenOdd = numbers.groupBy { it % 2 == 0 }
println("Grouped by Even/Odd: $groupedByEvenOdd")
}
Output
Grouped by Even/Odd: {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8]}
The output shows the list of integers grouped into two categories: even and odd numbers.
Example 2: Grouping Strings by Length
In this example, we shall use List groupBy() function to categorize strings based on their length.
Kotlin Program
fun main() {
val fruits = listOf("apple", "banana", "orange", "kiwi", "grape")
val groupedByLength = fruits.groupBy { it.length }
println("Grouped by Length: $groupedByLength")
}
Output
Grouped by Length: {5=[apple, grape], 6=[banana, orange], 4=[kiwi]}
The output shows the list of strings grouped based on their length.
Summary
In this tutorial, we have seen about List groupBy() function, its syntax, and how to use it for grouping elements in a list based on a specified criteria, with the help of example programs.