Lesson contents

Kotlin — Counting values with groupingBy

Kotlin groupingBy selects a key for each element and eachCount counts the elements in each group. Use the label itself as the key to count repeated labels.

A simple example

Look up one count

  1. Start with Key A has value 2
  2. Do this Look up A
  3. Result 2
The key identifies which stored value to read.
Lesson.kt
fun main() {
    val counts = mapOf("A" to 2)
    println(counts["A"])
}
Output
2
Advertisements

Count labels without relying on storage order

groupingBy defines the grouping key and eachCount computes the size of each group. getValue expects the requested key to exist. Use getOrDefault when missing keys are part of the input.

Scan order: Red, blue, red. Red team: 2 wristbands. Blue team: 1 wristband.
Count team wristbands

A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
fun main() {
    val counts = listOf("red", "blue", "red").groupingBy { it }.eachCount()
    for (color in listOf("red", "blue")) {
        println(color + " " + counts.getValue(color))
    }
}
Output
red 2
blue 1

The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.

Try it yourself

Insert another blue before the last red. What changes?

Check your answer

Both keys now have a count of two. The requested display order stays red, then blue.

Kotlin language documentation

Related tags

  • Kotlin
  • collections
  • frequency counts
  • lookup