Kotlin List groupByTo Function

The groupByTo function in Kotlin is used to group elements of a collection based on a given key selector function and store the grouped elements in a specified destination map. This function belongs to the Kotlin standard library and provides a flexible way to categorize elements into a custom map.

Table of Contents

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

Introduction

The groupByTo function allows you to group elements of a collection (such as a list) based on a given key selector function and store the resulting groups in a specified destination map. 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 and store the results in a custom map.

groupByTo Function Syntax

The syntax for the groupByTo function is as follows:

fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K): M

Parameters:

  • destination: The map where the grouped elements will be stored.
  • keySelector: A lambda function that takes an element of the original collection as input and returns a key for grouping.

Returns:

  • The destination map containing the grouped elements.

Understanding groupByTo

The groupByTo function iterates over each element in the original collection, applies the key selector function to it, and adds the element to the corresponding group in the destination map. 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 groupByTo, we will group a list of integers based on their parity (even or odd) and store the result in a custom map.

Example

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val groupedByParity = mutableMapOf<Boolean, MutableList<Int>>()
    numbers.groupByTo(groupedByParity) { 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 groupByTo to group a list of strings by their first character and store the result in a custom map.

Example

fun main() {
    val fruits = listOf("apple", "banana", "cherry", "apricot", "blueberry")
    val groupedByFirstChar = mutableMapOf<Char, MutableList<String>>()
    fruits.groupByTo(groupedByFirstChar) { 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 groupByTo with a custom key selector to group a list of objects and store the result in a custom map.

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 = mutableMapOf<Int, MutableList<Person>>()
    people.groupByTo(groupedByAge) { 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 groupByTo function can be used to group orders by their status, allowing you to categorize and process orders based on their current state, and store the result in a custom map.

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 = mutableMapOf<String, MutableList<Order>>()
    orders.groupByTo(groupedByStatus) { 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 groupByTo function in Kotlin is a powerful and flexible way to group elements of a collection based on a specified key selector function and store the resulting groups in a custom destination map. 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 groupByTo function, you can effectively manage and group collections in your Kotlin applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top