kotlinbeginner

Collection Transformations and Aggregations

Master Kotlin collection operations: groupBy, partition, associate, zip, windowed, and aggregate.

kotlin
data class Employee(val name: String, val dept: String, val salary: Double)

fun main() {
    val employees = listOf(
        Employee("Alice", "Engineering", 120_000.0),
        Employee("Bob", "Engineering", 110_000.0),
        Employee("Carol", "Sales", 95_000.0),
        Employee("Dave", "Sales", 105_000.0),
        Employee("Eve", "Engineering", 130_000.0)
    )

    // groupBy
    val byDept = employees.groupBy { it.dept }
    byDept.forEach { (dept, emps) ->
        println("$dept: ${emps.map { it.name }}")
    }

    // partition: split into two lists
    val (highPaid, lowPaid) = employees.partition { it.salary > 100_000 }
    println("High: ${highPaid.map { it.name }}")
    println("Low: ${lowPaid.map { it.name }}")

    // associate: build map
    val salaryMap = employees.associate { it.name to it.salary }
    println("Salaries: $salaryMap")

    // fold / reduce
    val totalSalary = employees.fold(0.0) { acc, emp -> acc + emp.salary }
    println("Total salary: $totalSalary")

    // maxByOrNull / minByOrNull
    val topEarner = employees.maxByOrNull { it.salary }
    println("Top earner: ${topEarner?.name}")

    // flatMap
    val tags = listOf(
        listOf("kotlin", "java"),
        listOf("python", "kotlin"),
        listOf("go", "rust")
    )
    println("Tags: ${tags.flatMap { it }.distinct().sorted()}")

    // zip
    val names = listOf("Alice", "Bob", "Carol")
    val scores = listOf(95, 87, 92)
    println("Results: ${names.zip(scores) { n, s -> "$n: $s" }}")

    // windowed + average
    val data = listOf(10, 20, 30, 25, 35, 40, 30)
    val movingAvg = data.windowed(3) { it.average() }
    println("Moving avg: ${movingAvg.map { "%.1f".format(it) }}")

    // chunked: batch processing
    (1..20).toList().chunked(5).forEach { println("Batch: $it") }

    // groupingBy + eachCount
    val words = "the quick brown fox jumps over the lazy brown dog".split(" ")
    println("Freq: ${words.groupingBy { it }.eachCount()}")
}

Use Cases

  • Data aggregation and reporting
  • Batch processing with chunked operations
  • Frequency analysis and grouping

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.