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
- Start with Key A has value 2
- Do this Look up A
- Result 2
fun main() {
val counts = mapOf("A" to 2)
println(counts["A"])
}
2
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.
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
fun main() {
val counts = listOf("red", "blue", "red").groupingBy { it }.eachCount()
for (color in listOf("red", "blue")) {
println(color + " " + counts.getValue(color))
}
}
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.