In Kotlin, List is a collection of ordered elements. You can create mutable or immutable lists depending on whether you want to change the list after it's created.
Creating Lists
val numbers = listOf(1, 2, 3, 4, 5) // Immutable
val fruits = mutableListOf("Apple", "Banana", "Mango") // Mutable
val fruits = listOf("Apple", "Banana", "Orange")
println(fruits[0]) // Output: Apple
Mutable List
val numbers = mutableListOf(1, 2, 3)
numbers.add(4)
println(numbers) // Output: [1, 2, 3, 4]
Immutable List operations
val list = listOf("a", "b", "c")
println(list[0]) // Access element by index
println(list.size) // Get size
println("b" in list) // Check if item exists
println(list.indexOf("c")) // Find index
println(list.contains("a")) // Check presence
println(list.first()) // Get first element
println(list.last()) // Get last element
MutableList operations
val list = mutableListOf("a", "b", "c")
list.add("d") // Add element
list.remove("b") // Remove element by value
list.removeAt(0) // Remove by index
list[0] = "z" // Update element
list.clear() // Remove all
list.addAll(listOf("x", "y")) // Add multiple
for (item in list) {
println(item)
}
list.forEach { println(it) }
Higher-order functions
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 } // Transform
val even = numbers.filter { it % 2 == 0 } // Filter
val sum = numbers.reduce { acc, i -> acc + i } // Sum up
val found = numbers.find { it > 3 } // Find first match
Access Elements
val first = list[0]
val last = list.last()
val size = list.size
val isEmpty = list.isEmpty()
Iterate Over List
for (item in list) {
println(item)
}
list.forEach {
println(it)
}
Add / Remove (for MutableList)
val list = mutableListOf("A", "B")
list.add("C") // Add single item
list.addAll(listOf("D")) // Add multiple items
list.remove("B") // Remove item by value
list.removeAt(0) // Remove item by index
list.clear() // Remove all items
Update Elements
list[1] = "Z" // Update value at index
Filter & Transform
val filtered = list.filter { it.startsWith("A") }
val uppercased = list.map { it.uppercase() }
Search
val containsA = list.contains("A")
val index = list.indexOf("C")
val found = list.find { it == "B" }
Sorting
val sorted = list.sorted()
val reversed = list.reversed()
val customSort = list.sortedBy { it.length }
Sublist & Slice
val sub = list.subList(1, 3) // From index 1 to 2
val slice = list.slice(0..1)
Distinct / Union / Intersect
val distinct = listOf("A", "A", "B").distinct()
val union = listOf("A", "B").union(listOf("B", "C"))
val intersect = listOf("A", "B").intersect(listOf("B", "C"))
Convert Between List & Other Types
val array = list.toTypedArray()
val set = list.toSet()
val joined = list.joinToString(", ")