Kotlin List and MutableList (with Examples)

Kotlin course · Collections · Lesson 28 of 51

A list is an ordered collection of items. It’s the collection you’ll use most in Kotlin. Kotlin has two kinds:

  • List: read-only. You can read it, but not add, remove or change items.
  • MutableList: you can add, remove and change items.

Creating lists

fun main() {
    val colors = listOf("Red", "Green", "Blue")        // List<String>
    val numbers = mutableListOf(1, 2, 3)              // MutableList<Int>
    val empty = emptyList<String>()
    val evens = List(5) { (it + 1) * 2 }

    println(colors)
    println(numbers)
    println(empty.isEmpty())
    println(evens)
}

Output:

[Red, Green, Blue]
[1, 2, 3]
true
[2, 4, 6, 8, 10]

Reading items

fun main() {
    val colors = listOf("Red", "Green", "Blue")
    println(colors[0])
    println(colors.first())
    println(colors.last())
    println(colors.size)
    println(colors.getOrNull(10))
    println(colors.getOrElse(10) { "Unknown" })
}

Output:

Red
Red
Blue
3
null
Unknown

Adding, removing and changing (MutableList)

fun main() {
    val cart = mutableListOf("Milk", "Bread")

    cart.add("Eggs")                 // add to the end
    cart.add(0, "Rice")              // add at an index
    cart.addAll(listOf("Tea", "Sugar"))
    println(cart)

    cart.remove("Bread")             // remove by value
    cart.removeAt(0)                 // remove by index
    cart[0] = "Toned Milk"           // change an item
    println(cart)

    cart.removeAll { it.startsWith("S") }
    println(cart)

    cart.clear()
    println(cart.size)
}

Output:

[Rice, Milk, Bread, Eggs, Tea, Sugar]
[Toned Milk, Eggs, Tea, Sugar]
[Toned Milk, Eggs, Tea]
0

Searching

fun main() {
    val names = listOf("Asha", "Ravi", "Meera", "Ravi")
    println(names.contains("Meera"))
    println("Zoya" in names)
    println(names.indexOf("Ravi"))
    println(names.lastIndexOf("Ravi"))
    println(names.find { it.length > 4 })
    println(names.count { it == "Ravi" })
}

Output:

true
false
1
3
Meera
2

Sorting

fun main() {
    val prices = mutableListOf(499, 99, 1299, 249)
    println(prices.sorted())              // new list, original unchanged
    println(prices.sortedDescending())
    prices.sort()                          // sorts this list itself
    println(prices)

    val words = listOf("banana", "Kiwi", "apple")
    println(words.sortedBy { it.lowercase() })
    println(words.sortedBy { it.length })
}

Output:

[99, 249, 499, 1299]
[1299, 499, 249, 99]
[99, 249, 499, 1299]
[apple, banana, Kiwi]
[Kiwi, apple, banana]

Functions ending in -ed (sorted, reversed, shuffled) return a new list. sort(), reverse() and shuffle() change a MutableList in place.

Sublists, slicing and combining

fun main() {
    val n = listOf(10, 20, 30, 40, 50, 60)
    println(n.take(3))
    println(n.drop(4))
    println(n.subList(1, 4))
    println(n.slice(listOf(0, 2, 4)))
    println(n.chunked(2))
    println(n + listOf(70, 80))
    println(n - 30)
}

Output:

[10, 20, 30]
[50, 60]
[20, 30, 40]
[10, 30, 50]
[[10, 20], [30, 40], [50, 60]]
[10, 20, 30, 40, 50, 60, 70, 80]
[10, 20, 40, 50, 60]

Read-only is not the same as immutable

A List variable only stops you from changing the list through that variable. If the same object is also a MutableList somewhere else, it can still change:

fun main() {
    val source = mutableListOf(1, 2)
    val view: List<Int> = source
    source.add(3)
    println(view)
}

Output:

[1, 2, 3]

A good rule: expose List from your classes, and keep the MutableList private.

Converting between List and MutableList

fun main() {
    val fixed = listOf("a", "b")
    val editable = fixed.toMutableList()
    editable.add("c")
    println(fixed)
    println(editable)
    println(editable.toList())
}

Output:

[a, b]
[a, b, c]
[a, b, c]

Common mistakes

  • Calling add on a List: it doesn’t compile. Use mutableListOf or toMutableList().
  • Expecting sorted() to change the list: it returns a new one. Use sort() on a MutableList.
  • Index out of bounds: use getOrNull, firstOrNull and lastOrNull when the list may be empty.

Exercise

Manage a to-do list: start with three tasks, mark one done by removing it, insert an urgent task at the top, and print the numbered list.

fun main() {
    val todo = mutableListOf("Buy groceries", "Pay electricity bill", "Call plumber")
    todo.remove("Pay electricity bill")
    todo.add(0, "Submit assignment (urgent)")

    todo.forEachIndexed { i, task -> println("${i + 1}. $task") }
    println("${todo.size} tasks left")
}

Output:

1. Submit assignment (urgent)
2. Buy groceries
3. Call plumber
3 tasks left

FAQ

What is the difference between List and MutableList in Kotlin?

A List is read-only. A MutableList adds functions like add, remove and set.

How do I add an item to a list in Kotlin?

Create it with mutableListOf(), then call add(). For a read-only list, use list + item, which returns a new list.

What is the difference between listOf and arrayListOf?

listOf returns a read-only List. arrayListOf returns an ArrayList, which is mutable. Prefer mutableListOf in Kotlin code.

WhatsApp us📞 Call now