Open In App

Kotlin Grouping

Last Updated : 15 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Kotlin, grouping means collecting items from a collection (like lists) based on some common property or category. The Kotlin Standard Library provides useful functions like groupBy() and groupingBy() to easily perform grouping operations on collections.

These functions help us handle and transform lists into meaningful maps based on certain conditions.

1. The groupBy() Function

The groupBy() function takes a lambda expression and returns a Map. The key is the result of the lambda (called the key selector) and the value is a list of all items that match that key.

Syntax:

fun <T, K> Iterable<T>.groupBy(
keySelector: (T) -> K
): Map<K, List<T>>

We can also provide a second lambda expression called the value transform function to modify the values in the resulting map.

Example:

Kotlin
fun main() {
    val fruits = listOf("apple", "apricot", "banana", "cherries", "berries", "cucumber")

    // Grouping fruits by their first letter (in uppercase)
    val result1 = fruits.groupBy { it.first().uppercaseChar() }
    println(result1)

    // Grouping fruits by their first letter (original case), but values transformed to uppercase
    val result2 = fruits.groupBy(
        keySelector = { it.first() },
        valueTransform = { it.uppercase() }
    )
    println(result2)
}

Output:

{A=[apple, apricot], B=[banana, berries], C=[cherries, cucumber]}
{a=[APPLE, APRICOT], b=[BANANA, BERRIES], c=[CHERRIES, CUCUMBER]}

In the first example, the fruits are grouped by the uppercase of their first letter. In the second example, the keys remain in lowercase, but the values are transformed to uppercase strings.


2. The groupingBy() Function

The groupingBy() function is another powerful tool for grouping elements when we want to perform operations on each group such as:

  • Counting items in each group.
  • Folding or reducing items to a single value in each group.
  • Aggregating items in a custom way.

We can perform these operations on groups:

  • eachcount(): it counts the items in each group.
  • fold() and reduce(): perform these operation on each group separately and return the result.
  • aggregate(): it is generic way of grouping means applying a specific operation subsequently to all the elements in each group and returns the result. So, it is used to implement custom operations.

Example:

Kotlin
fun main() {
    val fruits = listOf("apple", "apricot", "banana", "cherries", "berries", "cucumber")

    val countByFirstChar = fruits.groupingBy { it.first() }.eachCount()
    println(countByFirstChar)
}

Output:

{a=2, b=2, c=2}

Here, the list of fruits is grouped by their first letter, and the count of items in each group is shown.


Article Tags :

Similar Reads