kotlinbeginner

List Transformation Patterns

Master list operations: windowed, chunked, zip, fold, scan, partition, and custom transforms.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    // Chunked — split into sublists
    val chunks = numbers.chunked(3)
    println("Chunks: $chunks") // [[1,2,3],[4,5,6],[7,8,9],[10]]

    // Chunked with transform
    val sums = numbers.chunked(3) { chunk -> chunk.sum() }
    println("Chunk sums: $sums") // [6, 15, 24, 10]

    // Windowed — sliding window
    val windows = numbers.windowed(3)
    println("Windows: $windows") // [[1,2,3],[2,3,4],...]

    // Moving average
    val movingAvg = numbers.windowed(3) { it.average() }
    println("Moving avg: $movingAvg")

    // Windowed with step
    val stepped = numbers.windowed(3, step = 2)
    println("Stepped: $stepped")

    // Zip
    val names = listOf("Alice", "Bob", "Charlie")
    val ages = listOf(30, 25, 35)
    val people = names.zip(ages) { name, age -> "$name ($age)" }
    println("\nPeople: $people")

    // ZipWithNext — pairs of consecutive elements
    val diffs = numbers.zipWithNext { a, b -> b - a }
    println("Diffs: $diffs")

    // Fold — accumulate
    val product = numbers.fold(1) { acc, n -> acc * n }
    println("\nProduct: $product")

    // FoldRight
    val reversed = numbers.foldRight("") { n, acc -> "$acc$n " }
    println("FoldRight: $reversed")

    // Reduce (like fold but no initial value)
    val max = numbers.reduce { a, b -> if (a > b) a else b }
    println("Max: $max")

    // Scan — fold with intermediate results
    val runningSum = numbers.scan(0) { acc, n -> acc + n }
    println("Running sum: $runningSum")

    // Flatten
    val nested = listOf(listOf(1, 2), listOf(3, 4), listOf(5))
    println("\nFlattened: ${nested.flatten()}")

    val words = listOf("hello world", "foo bar")
    val chars = words.flatMap { it.split(" ") }
    println("Words: $chars")

    // Distinct operations
    val dupes = listOf(1, 2, 2, 3, 3, 3, 4)
    println("\nDistinct: ${dupes.distinct()}")

    data class Item(val name: String, val category: String)
    val items = listOf(
        Item("A", "food"), Item("B", "drink"),
        Item("C", "food"), Item("D", "drink")
    )
    val uniqueCategories = items.distinctBy { it.category }
    println("Unique categories: $uniqueCategories")

    // Sorting
    val sorted = items.sortedBy { it.name }
    val multiSort = items.sortedWith(
        compareBy<Item> { it.category }.thenByDescending { it.name }
    )
    println("\nSorted: $sorted")
    println("Multi-sorted: $multiSort")

    // Take / Drop
    println("\nFirst 3: ${numbers.take(3)}")
    println("Drop 7: ${numbers.drop(7)}")
    println("TakeWhile: ${numbers.takeWhile { it < 5 }}")
    println("DropWhile: ${numbers.dropWhile { it < 5 }}")

    // Partition
    val (evens, odds) = numbers.partition { it % 2 == 0 }
    println("\nEvens: $evens, Odds: $odds")

    // Indices and withIndex
    numbers.withIndex()
        .filter { (_, v) -> v > 7 }
        .forEach { (i, v) -> println("Index $i: $v") }

    // First / Last / Single
    println("\nFirst even: ${numbers.first { it % 2 == 0 }}")
    println("Last odd: ${numbers.last { it % 2 != 0 }}")
    println("FirstOrNull >100: ${numbers.firstOrNull { it > 100 }}")
}

Use Cases

  • Data processing pipelines
  • Sliding window calculations
  • Collection partitioning and grouping

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.