SyntaxStudy
Sign Up
Kotlin Lists, Sets and Maps
Kotlin Beginner 1 min read

Lists, Sets and Maps

Kotlin's collection library distinguishes between read-only and mutable interfaces. listOf(), setOf(), and mapOf() produce read-only views, while mutableListOf(), mutableSetOf(), and mutableMapOf() produce mutable counterparts. Read-only does not mean immutable: the underlying data may still be changed through a mutable reference. The standard library provides an enormous number of extension functions on collections: filter, map, flatMap, fold, reduce, groupBy, associate, zip, partition, and many more. These functions are chained in a pipeline style and, for large collections, can be evaluated lazily through sequences. Kotlin also ships with specialised array types (IntArray, DoubleArray, etc.) that map directly to primitive JVM arrays for performance-critical code, alongside the generic Array class.
Example
fun main() {
    // Read-only list
    val fruits = listOf("apple", "banana", "cherry", "date", "elderberry")

    // filter + map
    val longUpperFruits = fruits
        .filter  { it.length > 5 }
        .map     { it.uppercase() }
    println(longUpperFruits)   // [BANANA, CHERRY, ELDERBERRY]

    // flatMap — flatten nested collections
    val nested = listOf(listOf(1, 2), listOf(3, 4), listOf(5))
    println(nested.flatMap { it })   // [1, 2, 3, 4, 5]

    // groupBy
    val byLength = fruits.groupBy { it.length }
    println(byLength)

    // fold and reduce
    val sum    = listOf(1, 2, 3, 4, 5).fold(0) { acc, n -> acc + n }
    val product = listOf(1, 2, 3, 4, 5).reduce { acc, n -> acc * n }
    println("sum=$sum  product=$product")   // 15  120

    // Mutable map operations
    val scores = mutableMapOf("Alice" to 90, "Bob" to 75)
    scores["Carol"] = 88
    scores.getOrPut("Dave") { 70 }
    println(scores)

    // partition — splits into pair of lists
    val (evens, odds) = (1..10).partition { it % 2 == 0 }
    println("evens=$evens  odds=$odds")

    // zip
    val names  = listOf("Alice", "Bob", "Carol")
    val points = listOf(100, 200, 150)
    val zipped = names.zip(points)
    println(zipped)   // [(Alice, 100), (Bob, 200), (Carol, 150)]
}