๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Grouping

Grouping functions collect values into a map keyed by a shared feature. Other functions split one collection into pairs of smaller collections.

Grouping by a key

groupBy puts every word under its first letter. The whole map prints in the order the keys first appear.

fun main() {
    val words = listOf("ant", "ape", "bat", "bee", "cat")
    println(words.groupBy { it.first() })
}

Grouping with transformed values

The second lambda changes each value before grouping. Each word becomes its length.

fun main() {
    val words = listOf("ant", "apple", "bat", "bee", "cat")
    println(words.groupBy({ it.first() }, { it.length }))
}

Building a map directly

associate builds a pair for each value. associateBy uses each value itself and keeps the last value for a repeated key.

fun main() {
    val words = listOf("ant", "apricot", "bat")
    println(words.associate { it to it.length })
    println(words.associateBy { it.first() })
}

Splitting into two or more lists

partition returns a pair of lists and prints directly. chunked cuts the list into groups of two.

fun main() {
    val nums = listOf(1, 2, 3, 4, 5, 6)
    println(nums.partition { it % 2 == 0 })
    println(nums.chunked(2))
}

Example

fun main() {
    val words = listOf("ant", "ape", "bat", "bee", "cat", "cow")
    println(words.groupBy { it.first() })
    println(words.associateBy { it.first() })
    println(words.partition { it.length == 3 })
    println(words.chunked(4))
}

Key points

  • groupBy builds a map from a key to the list of values with that key.
  • groupBy can also transform each value before it enters the lists.
  • associate builds a map from pairs made for each value.
  • associateBy keeps the last value when two values share a key.
  • partition splits a collection into a pair of two lists.
  • chunked splits a collection into lists of a fixed size.

In this example, groupBy collects every word under its first letter. associateBy keeps only the last word for each letter. Every word has length 3, so partition puts all the words in the first list, and chunked makes groups of four and two.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does listOf("ant", "ape").associateBy { it.first() } return?