Using the 'groupBy' Function for Categorizing Collections

The 'groupBy' function is a powerful tool in Kotlin that allows you to group elements of a collection based on a specified criterion. This can be particularly useful when you want to categorize data into meaningful groups. For instance, you might want to group a list of items by their type or any other property. The result of 'groupBy' is a map where each key corresponds to a unique grouping criterion and the value is a list of items that fall under that key.

val items = listOf("Apple", "Banana", "Avocado", "Blueberry", "Cherry")

val groupedByFirstLetter = items.groupBy { it.first() }

println(groupedByFirstLetter)
// Output: {A=[Apple, Avocado], B=[Banana, Blueberry], C=[Cherry]}