Kotlin List โ listOf and mutableListOf with Examples
A List is an ordered collection of elements. Kotlin has immutable (listOf) and mutable (mutableListOf) variants.
What You Will Learn
- Create read-only lists with listOf
- Create mutable lists with mutableListOf
- Access elements by index
- Add and remove elements
- Iterate and filter lists
Read-Only List with listOf
listOf
fun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits)
println(fruits[0])
println(fruits.size)
println(fruits.contains("Banana"))
}fruits[0] accesses the first element. .size gives the element count. .contains() checks membership.
Mutable List with mutableListOf
mutableListOf
fun main() {
val nums = mutableListOf(1, 2, 3)
nums.add(4)
nums.add(0, 0) // insert at index 0
nums.remove(2) // remove value 2
nums.removeAt(0) // remove at index 0
println(nums)
}.add() appends an element or inserts at an index. .remove() removes by value. .removeAt() removes by index.
List Operations
filter, map, sorted
fun main() {
val numbers = listOf(5, 1, 8, 3, 9, 2)
println(numbers.filter { it > 4 })
println(numbers.map { it * 2 })
println(numbers.sorted())
println(numbers.sum())
println(numbers.max())
}filter returns elements matching a predicate. map transforms each element. sorted returns a new sorted list. sum and max are convenience functions.
Common List Functions
first, last, find, indexOf
fun main() {
val items = listOf(10, 20, 30, 40, 50)
println(items.first())
println(items.last())
println(items.find { it > 25 })
println(items.indexOf(30))
println(items.isEmpty())
}.first() and .last() return the first/last element. .find() returns the first element matching the predicate, or null. .indexOf() returns the position of the element (-1 if not found).
Practice Exercise
What prints? val list = mutableListOf(1,2,3) list.add(4) list.remove(2) println(list)
Quick Quiz
What is the difference between listOf and mutableListOf?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review