How to Group List in Kotlin: Simple Guide with Examples
In Kotlin, you can group elements of a list using the
groupBy function, which organizes items into a map based on a key you define. This function takes a lambda that returns the key for each element, grouping all elements with the same key together.Syntax
The groupBy function is called on a list and takes a lambda expression that defines the key for grouping. It returns a Map<K, List<T>> where K is the key type and T is the element type.
list.groupBy { element -> key }: Groups elements by the key returned from the lambda.- The lambda receives each element and returns the key to group by.
- The result is a map where each key maps to a list of elements sharing that key.
kotlin
val groupedMap = list.groupBy { element -> key }Example
This example groups a list of words by their first letter. It shows how groupBy collects words starting with the same letter into lists under that letter's key.
kotlin
fun main() {
val words = listOf("apple", "apricot", "banana", "blueberry", "cherry")
val grouped = words.groupBy { it.first() }
println(grouped)
}Output
{a=[apple, apricot], b=[banana, blueberry], c=[cherry]}
Common Pitfalls
One common mistake is forgetting that groupBy returns a map, not a list. Trying to use list functions directly on the result will cause errors.
Another pitfall is using a lambda that returns non-unique keys unintentionally, which groups elements unexpectedly.
kotlin
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// Wrong: expecting a list but groupBy returns a map
// val result = numbers.groupBy { it % 2 == 0 }
// println(result.size) // This is fine
// Correct usage:
val grouped = numbers.groupBy { it % 2 == 0 }
println(grouped) // Prints map with keys true and false
}Output
{false=[1, 3, 5], true=[2, 4]}
Quick Reference
- groupBy { keySelector }: Groups list elements by the key returned from
keySelector. - Returns a
Map<K, List<T>>where each key maps to a list of elements. - Use
map.keysto get all group keys. - Use
map.valuesto get all grouped lists.
Key Takeaways
Use Kotlin's groupBy function to group list elements by a key you define.
groupBy returns a map where each key points to a list of grouped elements.
The lambda passed to groupBy decides how elements are grouped by returning the key.
Remember that the result is a map, so use map operations to access groups.
Avoid using non-unique or unintended keys to prevent unexpected grouping.