Library contents

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

  1. Start with A, B, A
  2. Do this Count each key
  3. Result A has 2, B has 1
The second A increases the existing A count from one to two.

Syntax

Kotlin 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.

From the programval statuses = listOf("new", "sent", "new")
First output linenew=2
Lesson.kt
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))
    }
}
Output
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

Advertisements

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?

GivenN · S · N · N | count N
Worked result3

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?

Givenready · held · ready | count ready
Worked result2