Scala: Collections Cheat Sheet

Lists

Scala’s List[T] is a linked list of type T.

Below is an example of lists defined for various data types:

// List of Strings
val fruit: List[String] = List("bananas", "watermelons", "apples")

// List of Integers
val nums: List[Int] = List(1, 2, 3, 4)

// Empty List.
val empty: List[Nothing] = List()

// Two dimensional list
val dim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0, 1)
   )

Sets

A set is a collection of pairwise different elements of the same type.

Syntax:

// Empty set of integer type
var s : Set[Int] = Set()

// Set of integer type
var s : Set[Int] = Set(2,4,6,8)

or 

var s = Set(2,4,6,8)

Maps

A Map is a collection of key/value pairs. Any value can be retrieved based on its key.

Example

// Empty hash table whose keys are strings and values are integers:
var A:Map[Char,Int] = Map()

// A map with keys and values.
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

Tuples

Unlike an array or list, a tuple can hold objects with different types.

Example:

object Demo {
   def main(args: Array[String]) {
      val t = (4,3,2,1)
      val sum = t._1 + t._2 + t._3 + t._4

      println( "Sum of elements: "  + sum )
   }
}

Iterators

An iterator is not a collection, but rather a way to access the elements of a collection one by one.

Example:

object Demo {
   def main(args: Array[String]) {
      val it = Iterator("a", "number", "of", "words")
      
      while (it.hasNext){
         println(it.next())
      }
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *