📋 List
🎯 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
Phần tiêu đề “💡 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 đổival mutableList = mutableListOf(1, 2, 3) // Có thể thay đổi📝 Tạo List
Phần tiêu đề “📝 Tạo List”Immutable List
Phần tiêu đề “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
Phần tiêu đề “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
Phần tiêu đề “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ử
Phần tiêu đề “🔍 Truy cập phần tử”val fruits = listOf("Apple", "Banana", "Orange")
// Indexprintln(fruits[0]) // Appleprintln(fruits.get(1)) // Banana
// First/Lastprintln(fruits.first()) // Appleprintln(fruits.last()) // Orange
// Safe accessprintln(fruits.getOrNull(10)) // nullprintln(fruits.getOrElse(10) { "Default" }) // Default
// Findprintln(fruits.find { it.startsWith("B") }) // Banana🔄 Mutable List Operations
Phần tiêu đề “🔄 Mutable List Operations”val list = mutableListOf(1, 2, 3)
// Addlist.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]
// Removelist.remove(0) // Remove by valuelist.removeAt(0) // Remove by indexlist -= 7 // Remove using operatorlist.clear() // Remove all
// Updatelist[0] = 100 // Set by index🔗 List Operations (Functional)
Phần tiêu đề “🔗 List Operations (Functional)”Transform
Phần tiêu đề “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
Phần tiêu đề “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 }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
Phần tiêu đề “Aggregate”val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.sum()) // 15println(numbers.average()) // 3.0println(numbers.max()) // 5println(numbers.min()) // 1println(numbers.count()) // 5🛠️ Thực hành
Phần tiêu đề “🛠️ 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
Phần tiêu đề “📱 Trong Android”// RecyclerView dataval items: List<Item> = repository.getItems()adapter.submitList(items.filter { it.isVisible })
// LiveData transformationval users: LiveData<List<User>> = liveData.map { list -> list.sortedBy { it.name }}
// Spinner optionsval options = listOf("Option 1", "Option 2", "Option 3")ArrayAdapter(context, android.R.layout.simple_spinner_item, options)⚠️ Lưu ý quan trọng
Phần tiêu đề “⚠️ Lưu ý quan trọng”✅ Checklist - Tự kiểm tra
Phần tiêu đề “✅ 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