Scala (12): How to select collection in different scenario

Scala provides so many powerful collections, but how to select the suitable in different scenario. We need to consider several factors.

Hierarchy

  • 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.
    Screenshot 2016-05-13 14.27.59
  1. All collections can be traversed.
  2. Seq is Sequence of items with ordering.
  3. Set is a collection of items with no duplicates.
  4. Map is a key-value pairs.

Use

  • Iterable
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
  • Set
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
Map("a" -> 1, "b" -> 2)
Map(("a", 1), ("b", 2))

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s