CodeToLive

Kotlin Collections

Master Lists, Sets, and Maps in Kotlin.

Lists

// Immutable list
val numbers = listOf(1, 2, 3, 4)

// Mutable list
val mutableNumbers = mutableListOf(1, 2, 3)
mutableNumbers.add(4)

// Access elements
val first = numbers[0]  // 1
val last = numbers.last()  // 4

Sets

// Immutable set
val uniqueNumbers = setOf(1, 2, 3, 2, 1)  // [1, 2, 3]

// Mutable set
val mutableSet = mutableSetOf("A", "B")
mutableSet.add("C")

// Check membership
val containsA = "A" in mutableSet  // true

Maps

// Immutable map
val ages = mapOf(
    "Alice" to 25,
    "Bob" to 30
)

// Mutable map
val mutableAges = mutableMapOf(
    "Alice" to 25
)
mutableAges["Charlie"] = 35

// Access values
val aliceAge = ages["Alice"]  // 25

Collection Operations

val numbers = listOf(1, 2, 3, 4, 5)

// Filter
val evens = numbers.filter { it % 2 == 0 }  // [2, 4]

// Map
val squares = numbers.map { it * it }  // [1, 4, 9, 16, 25]

// Reduce
val sum = numbers.reduce { acc, num -> acc + num }  // 15

// Sort
val sorted = numbers.sortedDescending()  // [5, 4, 3, 2, 1]

Sequence (Lazy Evaluation)

val result = numbers.asSequence()
    .filter { it % 2 == 0 }
    .map { it * it }
    .toList()  // [4, 16]
← Back to Tutorials