List、Vector、Set、Map
核心集合
List、Vector、Set、Map 是 CoddyKit 上的免费 Scala for Backend Engineering & Functional Programming 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Scala for Backend Engineering & Functional Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Scala's core collections
Scala offers several immutable collections in its standard library. The four you will use most are List, Vector, Set, and Map. Each has different performance and semantics.
object Main {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3)
val vector = Vector(1, 2, 3)
val set = Set(1, 2, 3)
val map = Map("a" -> 1, "b" -> 2)
println(list)
println(vector)
println(set)
println(map)
}
}List: a linked list
List is a singly-linked list. Prepending with :: is O(1) and fast, but random access and appending are O(n). It is ideal for recursion and stack-like use.
object Main {
def main(args: Array[String]): Unit = {
val xs = List(2, 3, 4)
val prepended = 1 :: xs
println(prepended)
println("head: " + xs.head)
println("tail: " + xs.tail)
}
}Vector: balanced and general
Vector is an indexed sequence with effectively O(1) access, update, prepend, and append. When you need fast random access or a general-purpose sequence, prefer Vector over List.
object Main {
def main(args: Array[String]): Unit = {
val v = Vector(10, 20, 30, 40)
println(v(2))
val updated = v.updated(0, 99)
println(updated)
println(v :+ 50)
}
}Set: unique elements
A Set stores distinct elements with no duplicates and no guaranteed order. Membership tests with contains are fast.
object Main {
def main(args: Array[String]): Unit = {
val s = Set(1, 2, 2, 3, 3, 3)
println(s)
println(s.contains(2))
println(s + 4)
println(s - 1)
}
}Set operations
Sets support mathematical operations: union (|), intersect (&), and diff (−−).
object Main {
def main(args: Array[String]): Unit = {
val a = Set(1, 2, 3)
val b = Set(2, 3, 4)
println(a union b)
println(a intersect b)
println(a diff b)
}
}Map: key-value pairs
A Map associates keys with values. Keys are unique. Create entries with the -> arrow, and look up values with get (returns Option) or apply.
object Main {
def main(args: Array[String]): Unit = {
val ages = Map("Ann" -> 30, "Bob" -> 25)
println(ages("Ann"))
println(ages.get("Cara"))
println(ages.getOrElse("Cara", 0))
}
}Updating a Map immutably
Immutable maps return a new map when you add or remove entries; the original is unchanged. Use + to add or overwrite and - to remove.
object Main {
def main(args: Array[String]): Unit = {
val m = Map("a" -> 1)
val m2 = m + ("b" -> 2)
val m3 = m2 - "a"
println(m)
println(m2)
println(m3)
}
}Iterating over a Map
Iterating a Map gives you key-value tuples. You can destructure them directly in a for-comprehension or with pattern matching.
object Main {
def main(args: Array[String]): Unit = {
val scores = Map("math" -> 90, "art" -> 75)
for ((subject, score) <- scores) {
println(s"$subject: $score")
}
}
}Common methods shared by all
All these collections share a large common API: size, isEmpty, map, filter, foreach, and more. Learn the API once and it applies everywhere.
object Main {
def main(args: Array[String]): Unit = {
println(List(1, 2, 3).map(_ * 2))
println(Vector(1, 2, 3).map(_ * 2))
println(Set(1, 2, 3).map(_ * 2))
}
}Converting between collections
Conversion methods like toList, toVector, toSet, and toMap let you switch types easily. Converting to a Set removes duplicates.
object Main {
def main(args: Array[String]): Unit = {
val withDupes = List(1, 1, 2, 3, 3)
println(withDupes.toSet)
val pairs = List(("a", 1), ("b", 2))
println(pairs.toMap)
}
}Choosing the right collection
Quick guide:
List— recursion, fast prepend, head/tail processingVector— general-purpose, fast indexed accessSet— uniqueness and membership testsMap— key-based lookups
object Main {
def main(args: Array[String]): Unit = {
val ids = List(5, 3, 5, 1, 3)
val unique = ids.toSet
val indexed = ids.toVector
println(s"unique count: ${unique.size}")
println(s"third element: ${indexed(2)}")
}
}Quick Check
Which collection automatically removes duplicate elements?
Recap
You met Scala's core immutable collections:
- List — linked list, fast prepend
- Vector — indexed, well-balanced performance
- Set — unique elements with set algebra
- Map — key-value lookups with
get/getOrElse
They share a rich common API and convert into one another easily.
常见问题解答
「List、Vector、Set、Map」课时是免费的吗?
是的 — 「List、Vector、Set、Map」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Scala for Backend Engineering & Functional Programming 课程的其余内容,请升级到 CoddyKit PRO。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。
「List、Vector、Set、Map」这节课中我会学到什么?
核心集合 你通过在浏览器中直接运行的动手代码来练习 Scala for Backend Engineering & Functional Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Scala for Backend Engineering & Functional Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Scala for Backend Engineering & Functional Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「List、Vector、Set、Map」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Scala for Backend Engineering & Functional Programming 课中编写并运行代码吗?
能。每节 Scala for Backend Engineering & Functional Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。