KtKotlin

Kotlin: Data structures – code examples

Contents

Working with Lists

Data structures#list#filter#map#sortCompare in all languages
Use case: Manage collections of values: add, sort, filter.
fun main() {
    val zahlen = mutableListOf(5, 3, 8, 1)
    zahlen.add(10)
    zahlen.sort()
    println(zahlen)
    println(zahlen.filter { it > 3 }.map { it * 2 })
    println("${zahlen.size} ${zahlen.max()}")
}

filter and map are available directly on collections. Output: [1, 3, 5, 8, 10], [10, 16, 20], and 5 10.

Map (Dictionary)

Data structures#map#dictionary#elvisCompare in all languages
Use case: Store mappings, e.g. configurations or counters per key.
fun main() {
    val person = mutableMapOf<String, Any>("name" to "Ada", "alter" to 36)
    person["stadt"] = "London"
    for ((schluessel, wert) in person) {
        println("$schluessel = $wert")
    }
    println(person["email"] ?: "no email")
}

Accessing map[key] returns null for a missing key; the Elvis operator ?: provides a fallback value.

groupBy and partition

Data structures#groupby#partition#collections
Use case: Group or split records, e.g. users per city.
data class Person(val name: String, val stadt: String, val alter: Int)

fun main() {
    val leute = listOf(Person("Ada", "London", 36), Person("Bob", "Berlin", 25),
        Person("Eva", "Berlin", 31))
    println(leute.groupBy({ it.stadt }, { it.name }))
    val (aelter, juenger) = leute.partition { it.alter >= 30 }
    println("${aelter.size} / ${juenger.size}")
    println(leute.sumOf { it.alter })
}

groupBy builds a map of key → list, partition splits into two lists. Output: {London=[Ada], Berlin=[Bob, Eva]}, 2 / 1, 92.

Lazy Sequences

Data structures#sequence#lazy#yield
Use case: Process large or infinite amounts of data without creating intermediate lists.
fun main() {
    val ergebnis = generateSequence(1) { it + 1 }
        .filter { it % 3 == 0 }
        .map { it * it }
        .take(4)
        .toList()
    println(ergebnis)
    val fib = sequence {
        var a = 0
        var b = 1
        while (true) { yield(a); val t = a + b; a = b; b = t }
    }
    println(fib.take(8).toList())
}

Sequences work lazily: take(4) stops the infinite series. Output: [9, 36, 81, 144] and [0, 1, 1, 2, 3, 5, 8, 13].

Sorting by Multiple Criteria

Data structures#sort#comparator#sortedby
Use case: Order records, e.g. users by age descending, then by name.
data class Nutzer(val name: String, val alter: Int)

fun main() {
    val liste = listOf(Nutzer("Ada", 36), Nutzer("Bob", 25), Nutzer("Cy", 36))
    val sortiert = liste.sortedWith(compareByDescending<Nutzer> { it.alter }.thenBy { it.name })
    println(sortiert.map { it.name })
    println(liste.sortedBy { it.alter }.first().name)
    println(liste.maxByOrNull { it.alter }?.name)
}

sortedWith takes a composite comparator; sortedBy is enough for a single criterion. Output: [Ada, Cy, Bob], Bob, Ada.