Kotlin groupBy Function | Group List Elements by Key in Kotlin

The groupBy function in Kotlin is used to group elements of a collection based on a given key selector function. This function belongs to the Kotlin standard library and provides a convenient way to group elements into a map, where the keys are the results of the key selector function and the values are lists of elements that correspond to each key.

Table of Contents

  1. Introduction
  2. groupBy Function Syntax
  3. Understanding groupBy
  4. Examples
    • Basic Usage
    • Grouping a List of Strings
    • Grouping with Custom Key Selector
  5. Real-World Use Case
  6. Conclusion

Introduction

The groupBy function allows you to group elements of a collection (such as a list) based on a given key selector function. The resulting map contains keys that are the results of the key selector function and values that are lists of elements corresponding to each key. This is useful for scenarios where you need to categorize or partition elements based on specific criteria.

groupBy Function Syntax

The syntax for the groupBy function is as follows:

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

Parameters:

  • keySelector: A lambda function that takes an element of the original collection as input and returns a key for grouping.

Returns:

  • A map where the keys are the results of the key selector function and the values are lists of elements that correspond to each key.

Understanding groupBy

The groupBy function iterates over each element in the original collection, applies the key selector function to it, and groups the elements into a map based on the keys generated by the key selector. Each key in the map corresponds to a list of elements that share the same key.

Examples

Basic Usage

To demonstrate the basic usage of groupBy, we will group a list of integers based on their parity (even or odd).

Example

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val groupedByParity = numbers.groupBy { it % 2 == 0 }
    println("Grouped by parity: $groupedByParity")
}

Output:

Grouped by parity: {false=[1, 3, 5], true=[2, 4, 6]}

Grouping a List of Strings

This example shows how to use groupBy to group a list of strings by their first character.

Example

fun main() {
    val fruits = listOf("apple", "banana", "cherry", "apricot", "blueberry")
    val groupedByFirstChar = fruits.groupBy { it.first() }
    println("Grouped by first character: $groupedByFirstChar")
}

Output:

Grouped by first character: {a=[apple, apricot], b=[banana, blueberry], c=[cherry]}

Grouping with Custom Key Selector

This example demonstrates how to use groupBy with a custom key selector to group a list of objects.

Example

data class Person(val name: String, val age: Int)

fun main() {
    val people = listOf(
        Person("Alice", 30),
        Person("Bob", 25),
        Person("Charlie", 30),
        Person("David", 25)
    )
    val groupedByAge = people.groupBy { it.age }
    println("Grouped by age: $groupedByAge")
}

Output:

Grouped by age: {30=[Person(name=Alice, age=30), Person(name=Charlie, age=30)], 25=[Person(name=Bob, age=25), Person(name=David, age=25)]}

Real-World Use Case

Grouping Orders by Status

In real-world applications, the groupBy function can be used to group orders by their status, allowing you to categorize and process orders based on their current state.

Example

data class Order(val id: Int, val amount: Double, val status: String)

fun main() {
    val orders = listOf(
        Order(1, 100.0, "Shipped"),
        Order(2, 150.0, "Pending"),
        Order(3, 200.0, "Shipped"),
        Order(4, 80.0, "Pending"),
        Order(5, 120.0, "Delivered")
    )
    val groupedByStatus = orders.groupBy { it.status }
    println("Grouped by status: $groupedByStatus")
}

Output:

Grouped by status: {Shipped=[Order(id=1, amount=100.0, status=Shipped), Order(id=3, amount=200.0, status=Shipped)], Pending=[Order(id=2, amount=150.0, status=Pending), Order(id=4, amount=80.0, status=Pending)], Delivered=[Order(id=5, amount=120.0, status=Delivered)]}

Conclusion

The groupBy function in Kotlin is a powerful and convenient way to group elements of a collection based on a specified key selector function. It allows you to categorize and partition elements, making it useful for various applications, including data processing, categorization, and organization. 

By understanding and using the groupBy function, you can effectively manage and group collections in your Kotlin applications.

Comments