Collections in Scala

Reading Time: 2 minutes

Scala has a rich set of collection library. Collections are the containers that hold sequenced linear set of items. Collections may be strict or lazy. Lazy collections are collections that are not evaluated until they are accessed. Also, they can be mutable or immutable.  

ArrayBuffer

As we know that arrays are homogeneous and mutable. You can change the value but cannot change the size of array. To use mutable and indexed sequence whose size can change, ArrayBuffer class is used.To use ArrayBuffer first scala.collection.mutable.ArrayBuffer class is imported. Internally, ArrayBuffer is an array of element and also it stores the current size of the array. Elements are accessed in same way as that of array by passing the index value.

import scala.collection.mutable.ArrayBuffer
object Demo{
   def main(args : Array[String]){
      var name = ArrayBuffer[String]()
      name += "John"
      name += "David"
      println(name(1))// it will return David as output

   }
}

List

The List class is linear and immutable sequence. It means that it represents a linked-list that cannot be modified. You have to create a new list from existing one each and every time if you want to add or delete any element. A lot of operations can be applied on these list using various methods like head, tail, isEmpty, concat etc. The type of a list that has elements of type T is written as List[T].

object Demo{
  def main(args:Array[String]){
      val a:List[Int] = List(1,2,3,4)
      //Creating a new list by prepending the element 0 to existing list
      val b = 0:+ numbers
      //iterating over the elements of list
      for(i<-b) println(i)

   }
}

Vector

The Vector class is an indexed and immutable sequence. An indexed sequence provides much faster result than linear sequence except for head access and iteration algorithms.Vector performs much better in random access operations especially for large data collections. Vector is implemented using base 32 integer trie data structure.

object Demo{
  def main(args:Array[String]){
     var vector1 = Vector(2, 3, 4, 5)
     println(vector1)
     vector1.foreach((elem => print(elem+" "))
  }
}

Map

Map is an iterable collection of key-value pairs. Keys are unique and values can be retrieved based on its keys. However, data type used once for key and value must be consistent throughout.Maps can be classified into 2 types :- Mutable and Immutable.

object Demo{
   def main(args:Array[String]){
      val idNameMap = Map(1 -> "ABC", 
                        2 -> "IJK",
                        3 -> "XYZ")
      val name = idNameMap(1) 
      println(name)
    }
} 

Set

Set is a collection of pairwise elements of same type. It only contains unique element means there are no duplicate values in this collection. Set are also of 2 types mutable and immutable but by default it is mutable. It has various methods like  add, remove clear, size, etc. to enhance is usage.

object Main {
   def main(args: Array[String]) {  
       val countryset: Set[String] = Set("India","US","UK")
       println(countryset)
       //to print each element of set
       countryset.foreach((country:String)=>println(country))

    }
}

Thanks for reading it

Scala Future

Written by 

Amarjeet is a Software Consultant at Knoldus Software LLP. He has an overall experience of 2 years and 10 months.He has completed his Bachelor of Technology in Computer Science from National Institute of Technology, Hamirpur, Himachal Pradesh. He likes reading books, travelling and trekking.