List trong Kotlin
🎯 Mục tiêu: Nắm vững List - collection phổ biến nhất trong Kotlin, phân biệt Mutable vs Immutable.
💡 Khái niệm
List là tập hợp có thứ tự, cho phép phần tử trùng lặp.
Kotlin phân biệt rõ ràng:
List<T>: Immutable (chỉ đọc)MutableList<T>: Mutable (có thể thay đổi)
val immutableList = listOf(1, 2, 3) // Không thể thay đổi
val mutableList = mutableListOf(1, 2, 3) // Có thể thay đổi📝 Tạo List
Immutable List
val numbers = listOf(1, 2, 3, 4, 5)
val names = listOf("Alice", "Bob", "Charlie")
val empty = emptyList<String>()
val nullableList = listOfNotNull("a", null, "b") // ["a", "b"]Mutable List
val mutableNumbers = mutableListOf(1, 2, 3)
val arrayList = arrayListOf(1, 2, 3) // ArrayList cụ thểTạo List với size và giá trị mặc định
val zeros = List(5) { 0 } // [0, 0, 0, 0, 0]
val indices = List(5) { it } // [0, 1, 2, 3, 4]
val squares = List(5) { it * it } // [0, 1, 4, 9, 16]🔍 Truy cập phần tử
val fruits = listOf("Apple", "Banana", "Orange")
// Index
println(fruits[0]) // Apple
println(fruits.get(1)) // Banana
// First/Last
println(fruits.first()) // Apple
println(fruits.last()) // Orange
// Safe access
println(fruits.getOrNull(10)) // null
println(fruits.getOrElse(10) { "Default" }) // Default
// Find
println(fruits.find { it.startsWith("B") }) // Banana🔄 Mutable List Operations
val list = mutableListOf(1, 2, 3)
// Add
list.add(4) // [1, 2, 3, 4]
list.add(0, 0) // [0, 1, 2, 3, 4]
list += 5 // [0, 1, 2, 3, 4, 5]
list.addAll(listOf(6, 7)) // [0, 1, 2, 3, 4, 5, 6, 7]
// Remove
list.remove(0) // Remove by value
list.removeAt(0) // Remove by index
list -= 7 // Remove using operator
list.clear() // Remove all
// Update
list[0] = 100 // Set by index🔗 List Operations (Functional)
Transform
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 } // [2, 4, 6, 8, 10]
val strings = numbers.map { "Number $it" }
val flattened = listOf(listOf(1, 2), listOf(3, 4)).flatten() // [1, 2, 3, 4]Filter
val numbers = listOf(1, 2, 3, 4, 5, 6)
val even = numbers.filter { it % 2 == 0 } // [2, 4, 6]
val odd = numbers.filterNot { it % 2 == 0 } // [1, 3, 5]
val (evens, odds) = numbers.partition { it % 2 == 0 }Sort
val numbers = listOf(3, 1, 4, 1, 5, 9)
println(numbers.sorted()) // [1, 1, 3, 4, 5, 9]
println(numbers.sortedDescending()) // [9, 5, 4, 3, 1, 1]
println(numbers.sortedBy { -it }) // [9, 5, 4, 3, 1, 1]Aggregate
val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.sum()) // 15
println(numbers.average()) // 3.0
println(numbers.max()) // 5
println(numbers.min()) // 1
println(numbers.count()) // 5🛠️ Thực hành
Bài tập 1: Filter và transform
data class Student(val name: String, val score: Int)
fun main() {
val students = listOf(
Student("Alice", 85),
Student("Bob", 72),
Student("Charlie", 90),
Student("David", 65)
)
// TODO: Lấy tên của học sinh có điểm >= 80
}Lời giải:
fun main() {
val students = listOf(
Student("Alice", 85),
Student("Bob", 72),
Student("Charlie", 90),
Student("David", 65)
)
val topStudents = students
.filter { it.score >= 80 }
.map { it.name }
println(topStudents) // [Alice, Charlie]
}Bài tập 2: Group and aggregate
fun main() {
val sales = listOf(
Pair("Electronics", 1500),
Pair("Clothing", 800),
Pair("Electronics", 2000),
Pair("Food", 300),
Pair("Clothing", 600)
)
// TODO: Tính tổng doanh số theo category
}Lời giải:
fun main() {
val sales = listOf(
Pair("Electronics", 1500),
Pair("Clothing", 800),
Pair("Electronics", 2000),
Pair("Food", 300),
Pair("Clothing", 600)
)
val totalByCategory = sales
.groupBy { it.first }
.mapValues { (_, sales) -> sales.sumOf { it.second } }
println(totalByCategory)
// {Electronics=3500, Clothing=1400, Food=300}
}📱 Trong Android
// RecyclerView data
val items: List<Item> = repository.getItems()
adapter.submitList(items.filter { it.isVisible })
// LiveData transformation
val users: LiveData<List<User>> = liveData.map { list ->
list.sortedBy { it.name }
}
// Spinner options
val options = listOf("Option 1", "Option 2", "Option 3")
ArrayAdapter(context, android.R.layout.simple_spinner_item, options)⚠️ Lưu ý quan trọng
[!WARNING]
Listkhông có methods modify, nhưng backing list có thể mutable:val mutableList = mutableListOf(1, 2, 3) val list: List<Int> = mutableList // Upcasting mutableList.add(4) // Thay đổi cả list! println(list) // [1, 2, 3, 4]
[!TIP] Dùng
.toList()để copy:val safeCopy = mutableList.toList() // Immutable copy
✅ Checklist - Tự kiểm tra
Sau bài học này, bạn có thể:
- Phân biệt
ListvàMutableList - Tạo list với
listOf(),mutableListOf() - Truy cập phần tử an toàn với
getOrNull(),getOrElse() - Sử dụng
map,filter,sorted - Sử dụng
sum,average,max,min
Tiếp theo: Set
Last updated on