Scala - Collections



Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).

Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items.

For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones.

This chapter throws light on the most commonly used collection types and most frequently used operations over those collections.

Sr.No Collections with Description
1

Scala Lists

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

2

Scala Sets

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

3

Scala Maps

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

4

Scala Tuples

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

5

Scala Options

Option[T] provides a container for zero or one element of a given type.

6

Scala Iterators

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

Scala Lists

List is an ordered collection of elements. It is immutable by default. The following is the syntax for declaring a List variable -

val fruits: List[String] = List("Apple", "Banana", "Cherry")

Example

object Demo {
   def main(args: Array[String]) = {
      val fruits: List[String] = List("Apple", "Banana", "Cherry")
      // Print the list
      println(fruits)
      // Access elements
      println(fruits(0))
      println(fruits(1))
      println(fruits(2))
   }
}

Output

List(Apple, Banana, Cherry)
Apple
Banana
Cherry

Scala Sets

Set is a collection of unique elements. It is immutable by default. The following is the syntax for declaring a Set variable -

val fruits: Set[String] = Set("Apple", "Banana", "Cherry")

Example

object Demo {
   def main(args: Array[String]) = {
      val fruits: Set[String] = Set("Apple", "Banana", "Cherry")
      // Print the set
      println(fruits)
      // Check membership
      println(fruits.contains("Apple"))
      println(fruits.contains("Grapes"))
   }
}

Output

Set(Apple, Banana, Cherry)
true
false

Scala Maps

Map is a collection of key-value pairs. It is immutable by default. The following is the syntax for declaring a Map variable -

val colors: Map[String, String] = Map("red" -> "#FF0000", "green" -> "#00FF00", "blue" -> "#0000FF")

Example

object Demo {
   def main(args: Array[String]) = {
      val colors: Map[String, String] = Map("red" -> "#FF0000", 
         "green" -> "#00FF00", "blue" -> "#0000FF")
      // Print the map
      println(colors)
      // Access elements
      println(colors("red"))
      println(colors("green"))
      println(colors("blue"))
   }
}

Output

Map(red -> #FF0000, green -> #00FF00, blue -> #0000FF)
#FF0000
#00FF00
#0000FF

Scala Tuples

Tuple is a collection of elements of different types. The following is the syntax for declaring a Tuple variable -

val tuple: (String, Int, Boolean) = ("Scala", 42, true)

Example

object Demo {
   def main(args: Array[String]) = {
      val tuple: (String, Int, Boolean) = ("Scala", 42, true)
      // Print the tuple
      println(tuple)
      // Access elements
      println(tuple._1)
      println(tuple._2)
      println(tuple._3)
   }
} 

Output

(Scala, 42, true)
Scala
42
true

Scala Options

Option is a container for zero or one element of a given type. The following is the syntax for declaring an Option variable -

val someValue: Option[Int] = Some(42)
val noneValue: Option[Int] = None

Example

object Demo {
   def main(args: Array[String]) = {
      val someValue: Option[Int] = Some(42)
      val noneValue: Option[Int] = None
      // Print the options
      println(someValue)
      println(noneValue)
      // Access elements
      println(someValue.getOrElse(0))
      println(noneValue.getOrElse(0))
   }
}

Output

Some(42)
None
42
0

Scala Iterators

Iterator is not a collection, but rather a way to access the elements of a collection one by one. The following is the syntax for declaring an Iterator variable -

val iterator: Iterator[Int] = Iterator(1, 2, 3, 4, 5)

Example

object Demo {
   def main(args: Array[String]) = {
      val iterator: Iterator[Int] = Iterator(1, 2, 3, 4, 5)
      // Print the iterator
      println(iterator)
      // Iterate through elements
      while (iterator.hasNext) {
         println(iterator.next())
      }
   }
}

Output

non-empty iterator
1
2
3
4
5

Scala Vectors

Vector is an immutable indexed sequence that provides fast random access and updates. The following is the syntax for declaring a Vector variable -

val numbers: Vector[Int] = Vector(1, 2, 3, 4, 5)

Example

object Demo {
   def main(args: Array[String]) = {
      val numbers: Vector[Int] = Vector(1, 2, 3, 4, 5)
      // Print the vector
      println(numbers)
      // Access elements
      println(numbers(0))
      println(numbers(1))
      println(numbers(2))
      println(numbers(3))
      println(numbers(4))
   }
}

Output

Vector(1, 2, 3, 4, 5)
1
2
3
4
5

Scala Queues

Queue is a collection that follows the FIFO (First-In-First-Out) principle. The following is the syntax for declaring a Queue variable.

import scala.collection.immutable.Queue

val queue: Queue[Int] = Queue(1, 2, 3)

Example

import scala.collection.immutable.Queue

object Demo {
   def main(args: Array[String]) = {
      val queue: Queue[Int] = Queue(1, 2, 3)
      // Print the queue
      println(queue)
      // Enqueue an element
      val enqueueQueue = queue.enqueue(4)
      println(enqueueQueue)
      // Dequeue an element
      val (dequeueElement, dequeueQueue) = queue.dequeue
      println(dequeueElement)
      println(dequeueQueue)
   }
}

Output

Queue(1, 2, 3)
Queue(1, 2, 3, 4)
1
Queue(2, 3, 4)

Scala Stacks

Stack is a collection that follows the LIFO (Last-In-First-Out) principle. The following is the syntax for declaring a Stack variable -

import scala.collection.mutable.Stack

val stack: Stack[Int] = Stack(1, 2, 3)

Example

import scala.collection.mutable.Stack

object Demo {
   def main(args: Array[String]) = {
      val stack: Stack[Int] = Stack(1, 2, 3)
      // Print the stack
      println(stack)
      // Push an element
      stack.push(4)
      println(stack)
      // Pop an element
      val popElement = stack.pop
      println(popElement)
      println(stack)
   }
}

Output

Stack(1, 2, 3)
Stack(1, 2, 3, 4)
4
Stack(1, 2, 3)

Scala Sequences

Seq is a trait for indexed collections. It can be either mutable or immutable. The following is the syntax for declaring a Seq variable -

val seq: Seq[Int] = Seq(1, 2, 3, 4, 5)

Example

object Demo {
   def main(args: Array[String]) = {
      val seq: Seq[Int] = Seq(1, 2, 3, 4, 5)
      // Print the sequence
      println(seq)
      // Access elements
      println(seq(0))
      println(seq(1))
      println(seq(2))
      println(seq(3))
      println(seq(4))
   }
}

Output

Seq(1, 2, 3, 4, 5)
1
2
3
4
5

Scala Ranges

Range represents a sequence of integers and is commonly used in for-loops. The following is the syntax for declaring a Range variable.

val range: Range = 1 to 5

Example

object Demo {
   def main(args: Array[String]) = {
      val range: Range = 1 to 5
      // Print the range
      println(range)
      // Iterate through the range
      range.foreach(println)
   }
}

Output

Range(1, 2, 3, 4, 5)
1
2
3
4
5

Note that you need to save the above each program as Demo.scala. The following commands are used to compile and execute this program.

> scalac Demo.scala
> scala Demo

Then you can see your outputs.

Scala Collections Summary

  • Scala collections are containers that hold a sequence of elements and provide various operations and methods for these collections.
  • There are various types of collections in Scala, like, Lists, Sets, Maps, Tuples, Options, Iterators, Vectors, Queues, Stacks, Sequences, and Ranges.
  • Collections can be either mutable or immutable. Immutable collections cannot be modified after these are created. Whereas mutable collections can be changed anytime.
  • Common operations on collections are: adding, removing, accessing, and transforming elements.
  • Scala collections also support higher-order functions like, map, filter, and foreach for functional programming.
Advertisements