List, Vector, Set, Map
Core collections.
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)
}
}All lessons in this course
- List, Vector, Set, Map
- Transformations
- Folding and Reducing
- Grouping and Sorting