0
0
Kotlinprogramming~5 mins

GroupBy for categorization in Kotlin

Choose your learning style9 modes available
Introduction

GroupBy helps you organize items by putting similar things together. It makes it easy to see categories and count or list items in each group.

You want to sort a list of fruits by their color.
You have a list of students and want to group them by their grade.
You want to organize books by their author.
You want to count how many orders came from each city.
Syntax
Kotlin
val groupedMap: Map<KeyType, List<ValueType>> = list.groupBy { item -> keySelector(item) }

groupBy takes a function that tells how to group each item.

The result is a map where each key is a group, and the value is a list of items in that group.

Examples
This groups fruits by their first letter.
Kotlin
val fruits = listOf("apple", "banana", "cherry", "avocado")
val groupedByFirstLetter = fruits.groupBy { it.first() }
This groups numbers into "Even" and "Odd" categories.
Kotlin
val numbers = listOf(1, 2, 3, 4, 5, 6)
val groupedByEvenOdd = numbers.groupBy { if (it % 2 == 0) "Even" else "Odd" }
Sample Program

This program groups animal names by their first letter and prints each group.

Kotlin
fun main() {
    val animals = listOf("cat", "dog", "cow", "donkey", "camel")
    val groupedByFirstLetter = animals.groupBy { it.first() }

    for ((letter, group) in groupedByFirstLetter) {
        println("$letter: $group")
    }
}
OutputSuccess
Important Notes

The order of groups in the result map depends on the order of first appearance in the list.

You can use any logic inside the groupBy lambda to decide the grouping key.

Summary

GroupBy helps organize lists into categories based on a key.

The result is a map with keys as categories and values as lists of items.

It is useful for sorting, counting, or organizing data simply.