Sling Academy
Home/Kotlin/Grouping Lists by a Property in Kotlin

Grouping Lists by a Property in Kotlin

Last updated: December 05, 2024

Kotlin, a modern programming language favored by Android developers for its concise syntax and powerful features, provides a rich set of functionalities for handling collections. One of these is the ability to group list items by a property efficiently and effectively. Grouping is particularly useful when we want to organize a list into sublists based on a specific criterion. This article will explore the various ways to group lists by a property in Kotlin.

Using the groupBy Function

The groupBy function is a part of Kotlin's rich collection API and allows you to group elements of a collection into a Map based on a specified key. Here’s a simple example:

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

fun main() {
    val people = listOf(
        Person("Alice", 25),
        Person("Bob", 25),
        Person("Charlie", 30),
        Person("David", 20)
    )

    val groupedByAge = people.groupBy { it.age }
    println(groupedByAge)
}

In this example, we have a list of people, and we want to group them by age. The groupBy function is called with a lambda that specifies the key for grouping, which in this case is the age property. The result is a map where the keys are ages and the values are lists of people with that age.

Grouping by Multiple Properties

Sometimes you might want to group by multiple properties. While Kotlin does not natively support grouping by multiple fields using the groupBy function, you can achieve it by creating a data class or using Pair:

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

fun main() {
    val people = listOf(
        Person("Alice", 25, "New York"),
        Person("Bob", 25, "Los Angeles"),
        Person("Charlie", 30, "New York"),
        Person("David", 20, "Boston")
    )

    val groupedByAgeAndCity = people.groupBy { it.age to it.city }
    println(groupedByAgeAndCity)
}

In this case, each key in the resultant map is a Pair consisting of age and city. The values remain lists of people with the matching pair of age and city.

Implementing Custom Grouping Functions

While groupBy provides a straightforward solution, it sometimes might not align with complex grouping requirements. For such cases, implementing a custom grouping function may be necessary. Let’s create a custom function that categorizes people into different age groups:

fun main() {
    val people = listOf(
        Person("Alice", 25),
        Person("Bob", 25),
        Person("Charlie", 30),
        Person("David", 20)
    )

    val customGroups = categorizeByAgeGroup(people)
    println(customGroups)
}

fun categorizeByAgeGroup(people: List<Person>): Map<String, List<Person>> {
    return people.groupBy {
        when (it.age) {
            in 18..25 -> "Young Adult"
            in 26..35 -> "Adult"
            else -> "Other"
        }
    }
}

This function groups people based on age ranges and labels each group appropriately. By using when, we map ages to labels like 'Young Adult', 'Adult', etc., making the grouping semantically meaningful.

Conclusion

Kotlin's collection API, specifically the groupBy function, simplifies the task of grouping list entries by a particular property. Whether you are looking to group by a single property, a combination of multiple properties, or using custom logic, Kotlin provides the functionality you need to keep your code efficient and readable. Exploring and utilizing these functions not only makes your Kotlin projects more robust but also enhances your ability to manage and manipulate data effectively.

Next Article: Reversing and Shuffling Lists in Kotlin

Previous Article: Transforming Lists with `map` and `flatMap` in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin