Scala provides so many powerful collections, but how to select the suitable in different scenario. We need to consider several factors.
- Iterable[T] is any collection that can be iterated over, they provide an iterator method which gives us an Iterator to loop the elements) and foreach, Seq[T]s are collections that are ordered, Set[T]s are mathematical sets (unordered collections of unique items), and Map[T]s are associative arrays, also unordered.
- All collections can be traversed.
- Seq is Sequence of items with ordering.
- Set is a collection of items with no duplicates.
- Map is a key-value pairs.
def iterator: Iterator[A] def hasNext(): Boolean def next(): A e.g. Iterable(1,2,3) // Iterable[Int] = List(1,2,3) val i = Iterable(1,2,3).iterator i.hasNext // true i.next() // Int = 1
def contains(key: A): Boolean def +(elem: A): Set[A] def -(elem: A): Set[A] e.g. val s = Set(1,2,3) s.contains(2) // output: True s + 4 // Set(1,2,3,4) s - 2 // Set(1,3)
Map("a" -> 1, "b" -> 2) Map(("a", 1), ("b", 2))