Kotlin Collections

Working with lists, arrays, and data structures

📚 What are Kotlin Collections?

Collections are data structures that hold multiple elements. Kotlin provides powerful collection types like lists, sets, and maps with rich functionality for filtering, mapping, and transforming data efficiently and safely.


// Creating different collections
val numbers = listOf(1, 2, 3, 4, 5)
val mutableList = mutableListOf("A", "B", "C")

println("Numbers: $numbers")
println("Letters: $mutableList")
                                    

Output:

Numbers: [1, 2, 3, 4, 5]

Letters: [A, B, C]

Collection Types

📋

Lists

Ordered collections with duplicates

val list = listOf(1, 2, 3, 2)
🔢

Arrays

Fixed-size collections

val array = arrayOf(1, 2, 3)
✏️

Mutable Collections

Collections you can modify

val mutable = mutableListOf(1, 2)
🔄

Operations

Filter, map, and transform data

list.filter { it > 2 }

🔹 Creating Lists

Different ways to create and work with lists:

// Immutable list
val fruits = listOf("Apple", "Banana", "Orange")

// Mutable list
val colors = mutableListOf("Red", "Green", "Blue")
colors.add("Yellow")

// Empty lists
val emptyList = emptyList<String>()
val emptyMutable = mutableListOf<Int>()

println("Fruits: $fruits")
println("Colors: $colors")
println("First fruit: ${fruits[0]}")
println("List size: ${fruits.size}")

Output:

Fruits: [Apple, Banana, Orange]

Colors: [Red, Green, Blue, Yellow]

First fruit: Apple

List size: 3

🔹 Collection Operations

Transform and filter collections with powerful operations:

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

// Filter even numbers
val evenNumbers = numbers.filter { it % 2 == 0 }

// Map to squares
val squares = numbers.map { it * it }

// Find first number greater than 5
val firstBig = numbers.first { it > 5 }

// Check if any number is greater than 8
val hasLarge = numbers.any { it > 8 }

println("Even numbers: $evenNumbers")
println("Squares: $squares")
println("First > 5: $firstBig")
println("Has > 8: $hasLarge")

Output:

Even numbers: [2, 4, 6, 8, 10]

Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

First > 5: 6

Has > 8: true

🔹 Working with Arrays

Arrays are fixed-size collections with specific types:

// Different array types
val intArray = arrayOf(1, 2, 3, 4, 5)
val stringArray = arrayOf("Hello", "World")
val boolArray = booleanArrayOf(true, false, true)

// Array operations
val doubled = intArray.map { it * 2 }
val joined = stringArray.joinToString(" ")

// Convert between arrays and lists
val arrayToList = intArray.toList()
val listToArray = listOf(6, 7, 8).toTypedArray()

println("Int array: ${intArray.contentToString()}")
println("Doubled: $doubled")
println("Joined: $joined")
println("Array to list: $arrayToList")

Output:

Int array: [1, 2, 3, 4, 5]

Doubled: [2, 4, 6, 8, 10]

Joined: Hello World

Array to list: [1, 2, 3, 4, 5]

🧠 Test Your Knowledge

Which function creates an immutable list in Kotlin?