Transforming Collections

Article · 2:00

map, filter, fold and groupBy, and when a sequence beats a list.

Kotlin's standard library has roughly two hundred collection functions, and about six of them cover most real work. map transforms each element. filter keeps the ones matching a predicate. sortedBy orders by a computed key. groupBy turns a flat list into a map of lists. sumOf and fold reduce many values to one.

Chaining these replaces the loop-with-an-accumulator pattern almost entirely, and it reads as a description of the result rather than a recipe for computing it. The gain is not only brevity: there is no index, no mutable accumulator and no partially-built collection to get wrong.

The cost is allocation. Each step in a chain over a List produces a new List, so a four-step chain over ten thousand items allocates four intermediate lists. Converting to a Sequence with asSequence() makes the chain lazy - elements flow through all the steps one at a time, and nothing is materialised until a terminal operation such as toList. For small collections the eager version is faster, because laziness has its own overhead; for large ones or long chains, the sequence wins.

fold deserves specific attention because it generalises the others. It takes an initial value and a function combining the accumulator with each element, which is enough to express sum, product, max, and building a string or a map.

data class App(val name: String, val category: String, val downloads: Int)

fun main() {
    val apps = listOf(
        App("Notes", "productivity", 5_000),
        App("Tasks", "productivity", 12_000),
        App("Chess", "games", 8_000),
        App("Maze", "games", 300),
    )

    // Transform, filter and sort in one readable chain
    val popular = apps
        .filter { it.downloads > 1_000 }
        .sortedByDescending { it.downloads }
        .map { it.name }
    println(popular)                     // [Tasks, Chess, Notes]

    // groupBy turns a flat list into a map of lists
    val byCategory = apps.groupBy { it.category }
    println(byCategory.keys)             // [productivity, games]

    // sumOf and fold reduce many values to one
    println(apps.sumOf { it.downloads })                      // 25300
    println(apps.fold(0) { total, app -> total + app.downloads })

    // Lazy evaluation for a long chain over a large collection
    val firstBig = apps.asSequence()
        .map { it.downloads * 2 }
        .first { it > 10_000 }
    println(firstBig)
}

Discussion

No questions on this topic yet. Sign in to ask the first one.