Skip to Content
Kotlin📘 Ngôn ngữ KotlinSet - Mutable và Immutable

Set trong Kotlin - Mutable và Immutable

1. Giới thiệu

Set là collection chứa các phần tử duy nhất, không có thứ tự.

2. Immutable Set

fun main() { val numbers = setOf(1, 2, 3, 2, 1) println(numbers) // [1, 2, 3] val names = setOf("Alice", "Bob", "Alice") println(names) // [Alice, Bob] val empty = emptySet<String>() }

3. Mutable Set

fun main() { val numbers = mutableSetOf(1, 2, 3) numbers.add(4) numbers.add(2) // Không thêm vì đã có numbers.addAll(setOf(5, 6)) numbers.remove(1) println(numbers) // [2, 3, 4, 5, 6] }

4. Kiểm tra và truy cập

fun main() { val set = setOf(1, 2, 3, 4, 5) println(set.contains(3)) // true println(3 in set) // true println(set.size) // 5 println(set.isEmpty()) // false println(set.first()) // 1 }

5. Phép toán tập hợp

fun main() { val a = setOf(1, 2, 3, 4) val b = setOf(3, 4, 5, 6) // Hợp (Union) println(a union b) // [1, 2, 3, 4, 5, 6] // Giao (Intersection) println(a intersect b) // [3, 4] // Hiệu (Difference) println(a subtract b) // [1, 2] println(a - b) // [1, 2] }

6. Duyệt Set

fun main() { val set = setOf("apple", "banana", "cherry") for (item in set) { println(item) } set.forEach { println(it) } set.forEachIndexed { i, v -> println("$i: $v") } }

7. Filter và Map

fun main() { val numbers = setOf(1, 2, 3, 4, 5, 6) val evens = numbers.filter { it % 2 == 0 }.toSet() println(evens) // [2, 4, 6] val doubled = numbers.map { it * 2 }.toSet() println(doubled) // [2, 4, 6, 8, 10, 12] }

8. HashSet vs LinkedHashSet vs TreeSet

fun main() { // HashSet - không đảm bảo thứ tự val hashSet = hashSetOf(3, 1, 2) // LinkedHashSet - giữ thứ tự thêm vào val linkedSet = linkedSetOf(3, 1, 2) println(linkedSet) // [3, 1, 2] // TreeSet (SortedSet) - sắp xếp val sortedSet = sortedSetOf(3, 1, 2) println(sortedSet) // [1, 2, 3] }

9. Chuyển đổi

fun main() { val list = listOf(1, 2, 2, 3, 3, 3) // List -> Set (loại trùng) val set = list.toSet() println(set) // [1, 2, 3] // Set -> List val backToList = set.toList() // Set -> MutableSet val mutable = set.toMutableSet() }

10. Ví dụ thực tế

fun main() { // Loại bỏ trùng lặp val emails = listOf( "a@mail.com", "b@mail.com", "a@mail.com" ) val uniqueEmails = emails.toSet() // Kiểm tra quyền val userRoles = setOf("user", "editor") val requiredRoles = setOf("admin") if ((userRoles intersect requiredRoles).isNotEmpty()) { println("Access granted") } else { println("Access denied") } }

📝 Tóm tắt

  • setOf() tạo immutable set
  • mutableSetOf() tạo mutable set
  • Phần tử duy nhất, không trùng lặp
  • union, intersect, subtract cho phép toán
  • sortedSetOf() cho set có thứ tự
Last updated on