The 'groupBy' function in Kotlin allows you to categorize elements in a collection into a map based on a specified key. This is particularly useful when you need to organize data into groups, making it easier to process or display. For example, if you have a list of users with different roles, you can group them by their roles to manage them better.
val users = listOf(
User("Alice", "Admin"),
User("Bob", "User"),
User("Charlie", "Admin"),
User("David", "User")
)
val groupedByRole = users.groupBy { it.role }
println(groupedByRole)
// Output: {Admin=[User(name=Alice, role=Admin), User(name=Charlie, role=Admin)], User=[User(name=Bob, role=User), User(name=David, role=User)]}