Kotlin groupingBy and eachCount
groupingBy creates a grouping source, and eachCount traverses it to produce a map from each key to its frequency.
A simple example
groupingBy and eachCount
- Start with A, B, A
- Do this Count each key
- Result A has 2, B has 1
Syntax
statuses.groupingBy { it }.eachCount()
Run this example in Kotlin
Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Count order statuses without storing each group
An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.
fun main() {
val statuses = listOf("new", "sent", "new")
val counts = statuses.groupingBy { it }.eachCount()
for (status in listOf("new", "sent", "held")) {
println(status + "=" + (counts[status] ?: 0))
}
}
new=2 sent=1 held=0
A missing status has no map entry. Apply the Elvis operator to display zero for an expected category that had no orders.
Kotlin documentation for groupingBy and eachCount
Count north-door returns
A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?
Count ready print jobs
A print desk groups the current jobs by status. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?