The 'groupBy' function is a powerful tool for organizing elements of a collection into a map where each key corresponds to a specific criterion, and the value is a list of elements that match that criterion. This is particularly useful when you want to categorize items based on a property, such as grouping users by their age or products by their category.
data class User(val name: String, val age: Int)
val users = listOf(
User("Alice", 30),
User("Bob", 25),
User("Charlie", 30),
User("David", 25)
)
val groupedByAge = users.groupBy { it.age }
println(groupedByAge) // Output: {30=[User(name=Alice, age=30), User(name=Charlie, age=30)], 25=[User(name=Bob, age=25), User(name=David, age=25)]}