Kotlin Arrays and Lists

An array or list lets you store multiple values under a single name. Instead of creating ten separate variables for ten student names, you create one list that holds all ten. Think of it as a row of labeled boxes, all stored together.

Arrays

An array has a fixed size — once you create it with 5 slots, you cannot add or remove slots. You can only change the values in existing slots.

val scores = arrayOf(90, 85, 78, 92, 88)

println(scores[0])   // 90 — access by index (starts at 0)
println(scores[4])   // 88 — last element

scores[2] = 80       // Change the 3rd element

Diagram — Array Structure

Index:   0    1    2    3    4
       ┌────┬────┬────┬────┬────┐
Value: │ 90 │ 85 │ 78 │ 92 │ 88 │
       └────┴────┴────┴────┴────┘
              ↑
         scores[1] = 85

Typed Array Functions

val nums = intArrayOf(3, 1, 4, 1, 5)
val names = arrayOfNulls(3)   // ["null", "null", "null"]

println(nums.size)   // 5
println(nums.sum())  // 14
println(nums.max())  // 5
println(nums.min())  // 1

Lists

A list is more flexible than an array. Kotlin provides two kinds of lists:

  • listOf() — immutable. You cannot add, remove, or change items after creation.
  • mutableListOf() — mutable. You can add, remove, and change items freely.

Immutable List

val cities = listOf("Delhi", "Mumbai", "Pune", "Chennai")

println(cities[0])        // Delhi
println(cities.size)      // 4
println(cities.contains("Pune"))  // true

for (city in cities) {
    println(city)
}

Mutable List

val students = mutableListOf("Riya", "Arun", "Neha")

students.add("Kiran")          // Add to end
students.add(1, "Vikram")      // Insert at index 1
students.remove("Arun")        // Remove by value
students.removeAt(0)           // Remove by index
students[0] = "Smita"          // Update by index

println(students)

Diagram — List Operations

Start:     ["Riya", "Arun", "Neha"]

add("Kiran"):   ["Riya", "Arun", "Neha", "Kiran"]

add(1,"Vikram"):["Riya", "Vikram", "Arun", "Neha", "Kiran"]

remove("Arun"): ["Riya", "Vikram", "Neha", "Kiran"]

Common List Operations

val numbers = listOf(5, 3, 9, 1, 7, 2)

println(numbers.first())       // 5
println(numbers.last())        // 2
println(numbers.sorted())      // [1, 2, 3, 5, 7, 9]
println(numbers.sortedDescending()) // [9, 7, 5, 3, 2, 1]
println(numbers.reversed())    // [2, 7, 1, 9, 3, 5]
println(numbers.sum())         // 27
println(numbers.average())     // 4.5
println(numbers.count())       // 6
println(numbers.indexOf(9))    // 2

Filtering and Transforming Lists

val prices = listOf(120, 450, 80, 300, 60)

// Filter — keep items that match a condition
val affordable = prices.filter { it <= 100 }
println(affordable)   // [80, 60]

// Map — transform each item
val doubled = prices.map { it * 2 }
println(doubled)   // [240, 900, 160, 600, 120]

// Find — get first item matching condition
val first300Plus = prices.find { it > 300 }
println(first300Plus)   // 450

// Any / All / None
println(prices.any { it > 400 })    // true
println(prices.all { it > 50 })     // true
println(prices.none { it > 500 })   // true

2D Arrays — Grid of Values

A 2D array is an array of arrays — like a table with rows and columns. Use it to represent grids, game boards, or spreadsheet data.

val grid = arrayOf(
    intArrayOf(1, 2, 3),
    intArrayOf(4, 5, 6),
    intArrayOf(7, 8, 9)
)

println(grid[1][2])   // 6 (row 1, column 2)

// Visualized:
// [1][2][3]
// [4][5][6]
// [7][8][9]

Array vs List — When to Use Which

Feature           | Array          | List (immutable) | MutableList
------------------|----------------|------------------|-------------
Size              | Fixed          | Fixed            | Dynamic
Change values     | Yes            | No               | Yes
Add/remove items  | No             | No               | Yes
Performance       | Fastest        | Fast             | Fast
Best for          | Fixed data,    | Read-only data   | Collections
                  | performance    |                  | that change

Leave a Comment

Your email address will not be published. Required fields are marked *