• Articles
  • Tutorials
  • Interview Questions

Scala Collections - A Comprehensive Guide with Examples

Introduction to Scala Collections

Collections are the container of things that contains a random number of elements. All collection classes are found in the package scala.collection. Collections are of two types –

  • Mutable Collections
  • Immutable Collections

Mutable Collection – This type of collection is changed after it is created. All Mutable collection classes are found in the package scala.collection.mutable.
Immutable Collection – This type of collection will never change after it is created. All Immutable collection classes are found in the package scala.collection.immutable.

Watch this Informatica video

Video Thumbnail

Most Common Collection types are –

  • List
  • Map
  • Set
  • Tuple
  • Iterators

List

List is a collection of similar types of elements which are immutable. It represents the Linked list. If the list contains t types of elements then it can be represented as –

List[t]

The empty list is specified by Nil which is an object that represents an empty list. The method:: pronounced cons transforms an object and a list into a new list whose head is the object and whose tail is the first list.

val numbers: List[Int] = List(10, 20, 30 ,40)  //List of Integers
val empty: List[Int] = List()  // Empty List
val twodim: List[List[Int]] =
List (
List (0, 1, 0),
List (1, 1, 0)
)

List Constructors –

All lists are built from two more fundamental constructors that are Nil and::.Nil represents an empty list. The infix operator:: expresses list extension. That is, x:: xs represents a list whose first element is x, which is followed by list xs. You can also define the list as follows:

val numbers = 10 :: (20 :: (30 :: (40 :: Nil)))
val empty = Nil
val twodim = (0 :: (1 :: (0 :: Nil))) ::
(1 :: (1 :: (0 :: Nil))) :: Nil

For simplicity you can define the above list as follows:-

val numbers = 10 :: 20 :: 30 :: 40 :: Nil

Basic operations on lists –

Methods Description
head It returns the first element of a list.
tail It returns a list consisting of all elements except the first.
isEmpty It returns true if the list is empty.

e.g.

object Intellipaat {
def main(args: Array[String]) {
val numbers = 10 :: (20 :: (30 :: (40 :: Nil)))
val data = Nil
println( "Head of Number is : " + numbers.head )
println( "Tail of Number is : " + numebrs.tail )
println( "Check number is empty or not : " + numbers.isEmpty )
println( "Check data is empty or not : " + data.isEmpty )
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output:
Head of Number is: 10
The tail of Number is: List(20, 30, 40)
Check number is empty or not: False
Check data is empty or not: True

  • List.concat() –  It is used to perform concatenation of two lists.
  • List.fill() – It creates a list that contains the same element.
  • List.tabulate() – It converts the list in tabular form.
  • List.reverse – It is used to reverse the list elements.

Certification in Bigdata Analytics

Map (Hash Table)

It is a collection of key/value pairs where keys are unique and value is retrieved according to the key. Scala Online Training provides mutable and immutable versions of Map. If you want to use an immutable map then use Map and if you want to use a mutable map the use mutable. Map.
class hierarchy for scala map
e.g.

var I:Map[String ,Int] = Map()  // Creates empty hash table whose values are integers and keys are string type
val data = Map(
‘a’ ->10,
‘b’ -> 20,
‘c’->30,
‘d’ ->40
)

Basic Operations on Map:

All operations on maps can be expressed in terms of the following three methods:

Methods Description
keys It returns an iterable containing each key in the map.
values It returns an iterable containing each value in the map.
isEmpty It returns true if the map is empty otherwise false.

e.g.

object Intellipaat {
def main(args: Array[String]) {
val numbers = Map(
‘a’ ->10, ‘b’ -> 20, ‘c’->30, ‘d’ ->40
)
val data: Map[char, Int] = Map()
println( "Keys in Numbers are : " + numbers.keys )
println( "Values in numbers are : " + numbers.values )
println( "Check number is empty or not : " + numbers.isEmpty )
println( "Check data is empty or not : " + data.isEmpty )
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output :
Keys in Numbers are: Set(a, b, c, d)
Values in numbers are: MapLike (10, 20, 30, 40)
Check number is empty or not: False
Check data is empty or not: True

  • Map.++() – It is used to concatenate two or more maps.
  • Map.contains – It checks that if a given key exists in the map or not.
  • Foreach loop – It is used to print the keys and values of the map.

Become a Big Data Architect

Set

It is a collection of elements that are of the same type but do not contain the same elements. By default, scala uses an immutable set. Scala provides mutable and immutable versions of Set. If you want to use an immutable set then use Set and if you want to use mutable set the use mutable. Set.
class hierarchy for scala set

var i : Set[Int] = Set()    // Empty set of integer type
var i : Set[Int] = Set(10, 20, 30, 40)  // Set of integer type

Basic Operations on Set:

All operations on sets can be expressed in terms of the following three methods:

Methods Description
head It returns the first element of a set.
tail It returns a set consisting of all elements except the first.
isEmpty It returns true if the set is empty otherwise false.

e.g.

object Intellipaat {
def main(args: Array[String]) {
val numbers = Set(10, 20, 30, 40)
val data: Set[Int] = Set()
println( "Head of Number is : " + numbers.head )
println( "Tail of numbers is : " + numbers.tail )
println( "Check number is empty or not : " + numbers.isEmpty )
println( "Check data is empty or not : " + data.isEmpty )
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output:
Head of Number is: 10
The tail of Number is: Set(20, 30, 40)
Check number is empty or not: False
Check data is empty or not: True

  • Set.++() – It is used to concatenate the two or more sets.
  • Set.min – It is used to find the minimum value from the elements of the set.
  • Set.max() – It is used to find the maximum value from the elements of the set.
  • Set.intersect – It is used to find the common values between two sets.
  • Set.& – It is also used to find the common values between two sets.

Tuples

It is a collection of heterogeneous types of objects that is different types of objects which combine a fixed number of items together.
A tuple that contains an Int and a String:

val i = (1, "intellipaat")

To access tuple elements ‘._’ is used.
e.g.

object Intellipaat {
def main(args: Array[String]) {
val i = (10, 20, 30, 40)
val total = i._1 + i._2 + i._3 + i._4
println( "Total of Elements is : "  + total)
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
Total of elements is: 100

  • Tuple.productIterator() – It is used to iterate over all the elements of a Tuple.
  • Tuple.toString() – It is used to concatenate all the elements of the tuple into a string.
  • Tuple.swap – It is used to swap the elements of a Tuple.

Get 100% Hike!

Master Most in Demand Skills Now!

Iterator

It is used to access the elements of the collection one by one. Two important operations of an iterator are –

  • next
  • hasNext

next – It is used to return the next element of the iterator and move ahead of the state of the iterator.
hasNext – It is used to find out whether there are more elements to return.
e.g.

object Intellipaat {
def main(args: Array[String]) {
val i = Iterator("hello", "intellipaat", "a", "ecommerce", “site”)
while (i.hasNext){
println(i.next())
}
}
}

Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
 Output
hello
intellipaat
a
ecommerce
site

  • iterartor.min – It is used to return the minimum value elements form iterator.
  • iterator.max – It is used to return the maximum value elements form iterator.
  • iterator.size – It is used to return the number of elements in the iterator.
  • iterator.length – It is also used to return the number of elements in the iterator.

Course Schedule

Name Date Details
Big Data Course 30 Nov 2024(Sat-Sun) Weekend Batch View Details
07 Dec 2024(Sat-Sun) Weekend Batch
14 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Big Data Engineering

Abhijit is a Technical Research Analyst specialising in Big Data and Azure Data Engineering. He has 4+ years of experience in the Big data domain and provides consultancy services to several Fortune 500 companies. His expertise includes breaking down highly technical concepts into easy-to-understand content.