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.

Enroll yourself in Online Apache Spark and Scala Training and give a head-start to your career in Scala!

Watch this Informatica video

Scala Collections 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

Most Common Collection types are –

  • List
  • Map
  • Set
  • Tuple
  • Iterators


1. 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)
)

Wish to get certified in Scala! Learn Scala from top Scala experts and excel in your career with Intellipaat’s Scala certification!

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 –

MethodsDescription
headIt returns the first element of a list.
tailIt returns a list consisting of all elements except the first.
isEmptyIt 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

Are you interested in learning Scala from experts? Enroll in our Scala training in Singapore now!

  • 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.


2. 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:

MethodsDescription
keysIt returns an iterable containing each key in the map.
valuesIt returns an iterable containing each value in the map.
isEmptyIt 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.


3. 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:

MethodsDescription
headIt returns the first element of a set.
tailIt returns a set consisting of all elements except the first.
isEmptyIt 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

Visit our Big Data Community to get answers to all your queries!

  • 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.

4. 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.


5. 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

Looking for a job change in Scala? Check out this informative blog on Jobs in Scala and excel in your career!

  • 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.

Prepare yourself for the industry by going through this Top Apache Spark and Scala Interview Questions and Answers!

Recommended Videos

Leave a Reply

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

Solve : *
7 + 21 =