Sage-Code Laboratory

Scala Collection

A collection is a group of elements, all having the same type. There are two kind of collections: direct (indexed), or sequential (not indexed). Not all collections have index and direct access. Also some collections are mutable and some other are immutable. Some collections have versions that are both mutable or immutable.

In Scala, all collections are classes, each extending one trait. Of course they are! When you make a collection you must declare the class and data type of the elements. We will start explaining most used collections in order, as listed below:

Class MutabilityDescription
List immutable linked list, sequence
Vector immutable indexed sequence
Range immutable ordered sequence of integers
Set both collection of unque elements
Map both collection of key/value pairs
ArrayBuffermutable indexed sequence

Full Hierarchy

For curious people next you can study the diagram showing the full herarchy of traits and classes available for representing collections. In real life you will probably never use them all. We will explain only the most useful ones and make some examples.

Collection Hierarchy

The Hierarchy of Collection Classes


A List is a finite and immutable sequence of elements. It provide constant-time access to its first element and linear time for the rest of the list. Lists have a constant time/cost for adding a new element to the beginning of the list. When the list is short this is a very efficient data structure.


/* Make a list using companion object */
val days = List("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")

More: List API


A vector is a new collection type in Scala 2.8. Vectors allow accessing any element in constant time not dependent on the number of elements. The algorithms can access and modify elements of vectors at arbitrary locations, thus they can be more efficient than Lists.


/* We create two vectors as demo. */
val myVector = Vector(1, 2, 3, 4, 5)
val weekEnd: Vector[String] = Vector("Friday", "Saturday", "Sunday")

/* accessing elements by index */
println(s"weekEnd(0) = ${weekEnd(0)}")
println(s"weekEnd(1) = ${weekEnd(1)}")
println(s"weekEnd(2) = ${weekEnd(2)}")

More: Vector API


A Range is an ordered sequence of integers that are equally spaced apart. In mathematics we use square brackets to represent ranges.


For example: [0, 3] is a range, as is: [4,7) but 7 is excluded. We do not use this notation in programming. Instead, to create a range in Scala, we use the predefined keywords: "to","until" and "by" with limits: min-limit and max-limit.

/* Range expressions: */
0 to 3           // Range(0,1,2,3)  
4 until 7        // Range(4,5,6)  
4 to 10 by 2     // Range(4,6,8,10)
1 until 10 by 3  // Range(1,3,6,9)

More: Range API



Sets are iterable collections that contain unique elements. There are two versions available: immutable & mutable sets, in different libraries. To create an immutable set we use collection.immutable.Set() for mutable set we use collection.mutable.Set().


/* Create Set collection: */
val fruit = Set("apple", "orange", "peach", "banana") 


Maps are iterable collections consisting of (key, value) pairs that are actually tuples of two elements. The key can be integer, character or string. To access one element you can use the key like an index.


/* Create two identical Map collections: */
val thatMap = Map("x" -> 24, "y" -> 25, "z" -> 26)
val thisMap = Map(("x", 24), ("y", 25), ("z", 26))

More: Map API


This is the most popular among Java developers. It has similar methods. When use collections you must import them. That means they are external to your program and not known, until you import them.

Example 1:

In next example we create two ArrayBuffer collections. One is holding integers the other one is holding strings. Both are empyt at initialization time and get populated later with two elements each.

/* Using ArrayBuffer require import */
import scala.collection.mutable.ArrayBuffer

//create empty Arrays:
val ints = ArrayBuffer[Int]()
val names = ArrayBuffer[String]()

//create new elements 
ints += 1
ints += 2

//create new elements 
names += "scala"
names += "test"

Example 2:

When you create a collection, you can use arguments to initialize all the elements. In next example we create ArrayBuffer collection: "nums" with 3 initial elements, then we add other elements and then remove some.

/* Using type inference: */
val nums = ArrayBuffer(1, 2, 3) //initialized

// add multiple elements in one statement
nums += 5 += 6

// add multiple elements from another collection
nums ++= List(7, 8, 9)

// remove one element
nums -= 9

// remove multiple elements
nums -= 7 -= 8

// remove multiple elements using another collection
nums --= Array(5, 6)

More: ArrayBuffer API

Note: That's all I can say about collections for now. In the future is possible I will return here an continue my research. For deep learning you alwais have the API where you can dig in for more information. You will find some more examples in next page.

Study full: Collections API

Read next: Control Flow