Kotlin Sequence groupBy Function

The groupBy function in Kotlin is used to group elements of a sequence based on a specified key selector function. It is part of the Kotlin standard library and allows you to create a map where the keys are generated by 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 Sequence of Strings
    • Using groupBy with Custom Objects
    • Chaining groupBy with Other Functions
  5. Real-World Use Case
  6. Conclusion

Introduction

The groupBy function allows you to group elements of a sequence based on a specified key selector function. This is useful for scenarios where you need to categorize elements into groups, enabling efficient data organization and analysis.

groupBy Function Syntax

The syntax for the groupBy function is as follows:

fun <T, K> Sequence<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> fun <T, K, V> Sequence<T>.groupBy( keySelector: (T) -> K, valueTransform: (T) -> V ): Map<K, List<V>> 

Parameters:

  • keySelector: A lambda function that defines how each element in the sequence should be transformed into a key.
  • valueTransform (optional): A lambda function that defines how each element in the sequence should be transformed into a value. If not provided, the element itself is used as the value.

Returns:

  • A map containing the keys and lists of elements that correspond to each key.

Understanding groupBy

The groupBy function works by applying the key selector function to each element of the sequence, resulting in a key-value pair where the key is generated by the key selector and the value is a list of elements that share the same key. These pairs are then collected into a map, which is returned as the result.

Examples

Basic Usage

To demonstrate the basic usage of groupBy, we will create a sequence of integers and group them by their remainder when divided by 2.

Example

fun main() { val numbers = sequenceOf(1, 2, 3, 4, 5, 6) val groupedByRemainder = numbers.groupBy { it % 2 } println(groupedByRemainder) // Output: {1=[1, 3, 5], 0=[2, 4, 6]} } 

Output:

{1=[1, 3, 5], 0=[2, 4, 6]} 

Grouping a Sequence of Strings

This example shows how to group a sequence of strings by their first character.

Example

fun main() { val names = sequenceOf("Arjun", "Bhaskar", "Chitra", "Deepak", "Esha") val groupedByFirstChar = names.groupBy { it.first() } println(groupedByFirstChar) // Output: {A=[Arjun], B=[Bhaskar], C=[Chitra], D=[Deepak], E=[Esha]} } 

Output:

{A=[Arjun], B=[Bhaskar], C=[Chitra], D=[Deepak], E=[Esha]} 

Using groupBy with Custom Objects

You can use the groupBy function to group custom objects by a specific property.

Example

data class Person(val name: String, val age: Int) fun main() { val people = sequenceOf( Person("Arjun", 25), Person("Bhaskar", 30), Person("Chitra", 22), Person("Deepak", 28), Person("Esha", 26) ) val groupedByAge = people.groupBy { it.age / 10 * 10 } println(groupedByAge) // Output: {20=[Person(name=Arjun, age=25), Person(name=Chitra, age=22), Person(name=Esha, age=26)], 30=[Person(name=Bhaskar, age=30), Person(name=Deepak, age=28)]} } 

Output:

{20=[Person(name=Arjun, age=25), Person(name=Chitra, age=22), Person(name=Esha, age=26)], 30=[Person(name=Bhaskar, age=30), Person(name=Deepak, age=28)]} 

Chaining groupBy with Other Functions

The groupBy function can be chained with other sequence functions to perform more complex operations before grouping the elements.

Example

fun main() { val numbers = sequenceOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val groupedAndTransformed = numbers.filter { it % 2 == 0 } .groupBy { it / 2 } println(groupedAndTransformed) // Output: {1=[2], 2=[4], 3=[6], 4=[8], 5=[10]} } 

Output:

{1=[2], 2=[4], 3=[6], 4=[8], 5=[10]} 

Real-World Use Case

Grouping Products by Category

In real-world applications, the groupBy function can be used to group products or other items by a specific property, such as category or price range.

Example

data class Product(val name: String, val category: String, val price: Double) fun main() { val products = sequenceOf( Product("Laptop", "Electronics", 999.99), Product("Smartphone", "Electronics", 499.99), Product("Tablet", "Electronics", 299.99), Product("Smartwatch", "Wearables", 199.99), Product("Headphones", "Accessories", 99.99) ) val groupedByCategory = products.groupBy { it.category } println(groupedByCategory) // Output: {Electronics=[Product(name=Laptop, price=999.99), Product(name=Smartphone, price=499.99), Product(name=Tablet, price=299.99)], Wearables=[Product(name=Smartwatch, price=199.99)], Accessories=[Product(name=Headphones, price=99.99)]} } 

Output:

{Electronics=[Product(name=Laptop, price=999.99), Product(name=Smartphone, price=499.99), Product(name=Tablet, price=299.99)], Wearables=[Product(name=Smartwatch, price=199.99)], Accessories=[Product(name=Headphones, price=99.99)]} 

Conclusion

The groupBy function in Kotlin provides used for grouping elements of a sequence based on a specified key selector function. By understanding and using the groupBy function, you can efficiently manage and process data in your Kotlin applications, ensuring that you organize collections of elements in a structured and meaningful way.

Leave a Comment

Scroll to Top