Scala Scala Collections 2 — Questions and Answers
Question 1: What is a `Stream` (LazyList in Scala 2.13+) in Scala?
- A file input stream
- A lazily evaluated, potentially infinite list (Correct answer)
- A parallel collection
- A stream of bytes from network
Correct answer: A lazily evaluated, potentially infinite list
A `LazyList` (formerly `Stream`) is a lazily evaluated sequence where elements are computed on demand, supporting infinite sequences.
Question 2: What is the difference between `Seq` and `IndexedSeq` in Scala?
- Seq is mutable; IndexedSeq is not
- IndexedSeq guarantees O(1) random access by index; Seq only guarantees sequential traversal (Correct answer)
- Seq is a trait; IndexedSeq is a class
- IndexedSeq is sorted; Seq is not
Correct answer: IndexedSeq guarantees O(1) random access by index; Seq only guarantees sequential traversal
`IndexedSeq` extends `Seq` and guarantees efficient O(1) element access by index, while `Seq` only guarantees linear traversal.
Question 3: How do you convert a Scala Map's keys to a Set?
- map.keySet
- map.keys.toSet
- map.keys
- Both map.keySet and map.keys.toSet work (Correct answer)
Correct answer: Both map.keySet and map.keys.toSet work
Both `map.keySet` (returns a `Set`) and `map.keys.toSet` produce a `Set` containing the map's keys in Scala.
Question 4: What does `distinct` do on a Scala Seq?
- Sorts elements
- Returns only unique elements in their original order (Correct answer)
- Removes None values
- Compares adjacent elements
Correct answer: Returns only unique elements in their original order
`distinct` returns a new sequence with duplicate elements removed, preserving the order of first occurrence.
Question 5: What is a `Map` in Scala and how do you create one?
- A function applied to collections
- An immutable key-value store created with Map(key -> value) (Correct answer)
- A mutable hash table
- A sorted collection of pairs
Correct answer: An immutable key-value store created with Map(key -> value)
A Scala `Map[K,V]` stores key-value pairs; the default `Map` is immutable and created with `Map(key -> value, ...)`.
Question 6: How do you merge two immutable Maps in Scala?
- map1.add(map2)
- map1 ++ map2 (Correct answer)
- map1.merge(map2)
- Map.combine(map1, map2)
Correct answer: map1 ++ map2
The `++` operator merges two Maps in Scala, with the right-hand map's values winning on key conflicts.
What is a `Stream` (LazyList in Scala 2.13+) in Scala?