0Pricing
Android Academy · 课时

Kotlin 集合

使用 List、Set 和 Map。掌握 filter、map、sortedBy、forEach、find、any、all 等函数式运算符,并串联操作以简洁地转换数据。

Kotlin 集合 是 CoddyKit 上的免费 Android Academy 课时。 这是第 1 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Android Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Android Academy 课程共包含 6 节课。

集合概览

Kotlin 标准库提供三种主要的集合类型:

  • List——有序的元素序列(可以包含重复元素)
  • Set——不重复的元素,不保证特定顺序
  • Map——键值对,键必须唯一

每种类型都有不可变版本(只读)和可变版本(可以修改)。

列表:listOf 与 mutableListOf

使用工厂函数创建列表:

fun main() {
    // Immutable — cannot add/remove items
    val fruits = listOf("Apple", "Banana", "Cherry")
    println(fruits[0])       // Apple
    println(fruits.size)     // 3

    // Mutable — can modify
    val scores = mutableListOf(10, 20, 30)
    scores.add(40)
    scores.removeAt(0)       // remove index 0
    println(scores)          // [20, 30, 40]
}

Map:键值对

使用 mapOf 和 mutableMapOf 创建 Map。通过键访问值:

fun main() {
    val capitals = mapOf(
        "Turkey" to "Ankara",
        "Germany" to "Berlin",
        "Japan" to "Tokyo"
    )

    println(capitals["Turkey"])      // Ankara
    println(capitals["France"])      // null (not found)
    println(capitals.getOrDefault("France", "Unknown")) // Unknown

    // Iterate
    for ((country, city) in capitals) {
        println("$country -> $city")
    }
}

filter——筛选元素

filter 会返回一个新列表,其中只包含符合条件的元素:

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8)

    val evens = numbers.filter { it % 2 == 0 }
    println(evens)   // [2, 4, 6, 8]

    val names = listOf("Alice", "Bob", "Anna", "Charlie")
    val aNames = names.filter { it.startsWith("A") }
    println(aNames)  // [Alice, Anna]
}

map——转换元素

map 会转换每个元素,并返回一个新列表:

fun main() {
    val prices = listOf(10.0, 20.0, 30.0)

    // Apply 10% tax
    val withTax = prices.map { it * 1.1 }
    println(withTax)  // [11.0, 22.0, 33.0]

    val names = listOf("alice", "bob", "carol")
    val upper = names.map { it.uppercase() }
    println(upper)    // [ALICE, BOB, CAROL]
}

sortedBy 与 sortedByDescending

根据属性对列表排序:

data class Student(val name: String, val grade: Int)

fun main() {
    val students = listOf(
        Student("Alice", 88),
        Student("Bob", 95),
        Student("Carol", 72)
    )

    val byGrade = students.sortedByDescending { it.grade }
    for (s in byGrade) println("${s.name}: ${s.grade}")
    // Bob: 95
    // Alice: 88
    // Carol: 72
}

forEach 与 find

另外两个实用的集合函数:

  • forEach——遍历元素,但不构建结果
  • find——返回第一个符合条件的元素,如果没有则返回 null

链式操作

将多个操作串联起来,以简洁地转换数据:

data class Product(val name: String, val price: Double, val inStock: Boolean)

fun main() {
    val products = listOf(
        Product("Laptop", 999.0, true),
        Product("Mouse", 29.0, false),
        Product("Keyboard", 79.0, true),
        Product("Monitor", 349.0, true)
    )

    // In-stock products under $500, sorted by price
    val result = products
        .filter { it.inStock && it.price < 500 }
        .sortedBy { it.price }
        .map { "${it.name}: ${it.price}" }

    result.forEach { println(it) }
}

any、all、count

用于快速获取结果的聚合函数:

  • any { condition }——至少有一个元素符合条件时返回 true
  • all { condition }——每个元素都符合条件时返回 true
  • count { condition }——符合条件的元素数量
  • sumOf { it.price }——对数值属性求和

快速检查

如果要获取列表中满足某个条件的所有元素,应使用哪个函数?

回顾:Kotlin 集合

现在,您可以在 Kotlin 中高效地处理数据:

  • listOf / mutableListOf、mapOf / mutableMapOf
  • filter——选择符合条件的元素
  • map——转换元素
  • sortedBy / sortedByDescending
  • 将操作串联起来,构建清晰、易读的数据处理流程

下一步:使用 RecyclerView 在屏幕上显示列表。

常见问题解答

「Kotlin 集合」课时是免费的吗?

是的 — 「Kotlin 集合」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Android Academy 课程的其余内容,请升级到 CoddyKit PRO。 Android Academy 课程共包含 6 节课。

「Kotlin 集合」这节课中我会学到什么?

使用 List、Set 和 Map。掌握 filter、map、sortedBy、forEach、find、any、all 等函数式运算符,并串联操作以简洁地转换数据。 你通过在浏览器中直接运行的动手代码来练习 Android Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Android Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Android Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 6 节。

「Kotlin 集合」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Android Academy 课中编写并运行代码吗?

能。每节 Android Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Kotlin 集合
  2. RecyclerView 基础
  3. RecyclerView 点击事件
  4. SharedPreferences
  5. DataStore 偏好设置
  6. 适配器与 DiffUtil
← 返回 Android Academy