集合#

Kotlin 的集合(Collections)分為 唯讀(Read-only)可變(Mutable) 兩大類型,主要包含 List、Set 和 Map 三種結構。


1. List#

List 是有序的集合,允許重複元素。

唯讀 List#

1
2
3
4
5
6
fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    println(fruits)        // 輸出:[Apple, Banana, Cherry]
    println(fruits[1])     // 輸出:Banana
    println(fruits.size)   // 輸出:3
}

可變 List(MutableList)#

1
2
3
4
5
6
7
8
fun main() {
    val fruits = mutableListOf("Apple", "Banana")
    fruits.add("Cherry")
    fruits.remove("Apple")
    fruits[0] = "Mango"

    println(fruits) // 輸出:[Mango, Cherry]
}

常用 List 操作#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fun main() {
    val numbers = listOf(3, 1, 4, 1, 5, 9, 2, 6)

    println(numbers.first())          // 輸出:3
    println(numbers.last())           // 輸出:6
    println(numbers.max())            // 輸出:9
    println(numbers.min())            // 輸出:1
    println(numbers.sum())            // 輸出:31
    println(numbers.sorted())         // 輸出:[1, 1, 2, 3, 4, 5, 6, 9]
    println(numbers.reversed())       // 輸出:[6, 2, 9, 5, 1, 4, 1, 3]
    println(numbers.distinct())       // 輸出:[3, 1, 4, 5, 9, 2, 6](移除重複)
    println(numbers.contains(5))      // 輸出:true
    println(numbers.indexOf(4))       // 輸出:2
}

2. Set#

Set 是不允許重複元素的集合,且不保證順序。

唯讀 Set#

1
2
3
4
5
fun main() {
    val colors = setOf("Red", "Green", "Blue", "Red")
    println(colors) // 輸出:[Red, Green, Blue](重複的 Red 被移除)
    println(colors.size) // 輸出:3
}

可變 Set(MutableSet)#

1
2
3
4
5
6
7
fun main() {
    val tags = mutableSetOf("kotlin", "android")
    tags.add("java")
    tags.add("kotlin") // 重複,不會加入

    println(tags) // 輸出:[kotlin, android, java]
}

Set 集合運算#

1
2
3
4
5
6
7
8
fun main() {
    val a = setOf(1, 2, 3, 4)
    val b = setOf(3, 4, 5, 6)

    println(a union b)        // 聯集:[1, 2, 3, 4, 5, 6]
    println(a intersect b)    // 交集:[3, 4]
    println(a subtract b)     // 差集:[1, 2]
}

3. Map#

Map 儲存鍵值對(Key-Value),每個鍵唯一。

唯讀 Map#

1
2
3
4
5
6
7
8
9
fun main() {
    val scores = mapOf("Alice" to 90, "Bob" to 85, "Carol" to 92)

    println(scores["Alice"])          // 輸出:90
    println(scores.getOrDefault("Dave", 0)) // 輸出:0
    println(scores.keys)              // 輸出:[Alice, Bob, Carol]
    println(scores.values)            // 輸出:[90, 85, 92]
    println(scores.size)              // 輸出:3
}

可變 Map(MutableMap)#

1
2
3
4
5
6
7
8
fun main() {
    val scores = mutableMapOf("Alice" to 90, "Bob" to 85)
    scores["Carol"] = 92        // 新增
    scores["Alice"] = 95        // 修改
    scores.remove("Bob")        // 刪除

    println(scores) // 輸出:{Alice=95, Carol=92}
}

遍歷 Map#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fun main() {
    val scores = mapOf("Alice" to 90, "Bob" to 85, "Carol" to 92)

    for ((name, score) in scores) {
        println("$name$score 分")
    }
    // 輸出:
    // Alice:90 分
    // Bob:85 分
    // Carol:92 分
}

4. 集合的選擇指南#

情境建議集合
有順序、可重複、只讀listOf()
有順序、可重複、需修改mutableListOf()
不重複、只讀setOf()
不重複、需修改mutableSetOf()
鍵值對、只讀mapOf()
鍵值對、需修改mutableMapOf()

5. 實用小技巧#

集合轉型#

1
2
3
4
5
6
7
8
fun main() {
    val list = listOf(3, 1, 2, 1, 3)
    val set = list.toSet()         // 轉為 Set(移除重複)
    val mutableList = list.toMutableList() // 轉為可變 List

    println(set)         // 輸出:[3, 1, 2]
    println(mutableList) // 輸出:[3, 1, 2, 1, 3]
}

建立空集合#

1
2
3
val emptyList: List<String> = emptyList()
val emptySet: Set<Int> = emptySet()
val emptyMap: Map<String, Int> = emptyMap()

groupBy:依條件分組#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
data class Student(val name: String, val grade: String)

fun main() {
    val students = listOf(
        Student("Alice", "A"),
        Student("Bob", "B"),
        Student("Carol", "A"),
        Student("Dave", "B")
    )

    val grouped = students.groupBy { it.grade }
    println(grouped["A"]?.map { it.name }) // 輸出:[Alice, Carol]
    println(grouped["B"]?.map { it.name }) // 輸出:[Bob, Dave]
}

Reference#

https://kotlinlang.org/docs/collections-overview.html