Scala Collections Example

Filed Under: Scala

Scala Collections are the containers that hold sequenced linear set of items like List, Set, Tuple, Option, Map etc. Collections may be strict or lazy. The memory is not allocated until they are accessed. Collections can be mutable or immutable.

In this article, let us understand List and Set.

Scala List

The elements of the list have same data type. Lists are similar to arrays with two differences that is Lists are immutable and list represents a linked list whereas arrays are flat.

List is represented as List[T] where T is the data-type of the elements.

Consider an example;


val StudentNames[String] = List("Rohan", "Andreas", "Rob", "John")

Empty list can be created as


val em: List[Nothing] = List()

Two dimensional list can be created as


val twodim: List[List[Int]] =
   List(
      List(1, 0, 0),
      List(0, 1, 0),
      List(0, 0, 1)
   )

Basic Operations on Scala List

The basic operations include;

head: returns first element in the list.

tail: returns all the elements except the first element in the list.

isempty: returns true if the list is empty.

Consider an example for these operations;


object Student {
def main(args:Array[String]) {
    val names= "Harry" :: ("Adam" :: ("Jill" :: Nil))
    val age = Nil
      println( "Head of names array : " + names.head )
      println( "Tail of names array : " + names.tail )
      println( "Check if names is empty : " + names.isEmpty )
      println( "Check if age is empty : " + age.isEmpty )
   }
}

We are creating student object with two lists – names and age. We are invoking the head, tail and empty method on the array names and age.

Run the output by typing Student.main(null) and you will see below output.


Head of names array : Harry
Tail of names array : List(Adam, Jill)
Check if names is empty : false
Check if age is empty : true

You can also save the above code in Student.scala file and run as


$scalac Student.scala
$scala Student
Head of names array : Harry
Tail of names array : List(Adam, Jill)
Check if names is empty : false
Check if age is empty : true

Scala-List-Example

Scala Concatenating lists

To concatenate lists we use ::: or List.:::() or concat method to join two or more lists.

Consider an example of how to concatenate the lists


object Country {
	def main(args:Array[String]) {
	val country_1 =  List("India","SriLanka","Algeria")
	val country_2 = List("Austria","Belgium","Canada")

	val country = country_1 ::: country_2
	println( "country_1 ::: country_2 : " + country )

	val cont = country_1.:::(country_2)
            println( "country_1.:::(country_2) : " + cont )
	val con = List.concat(country_1, country_2)
            println( "List.concat(country_1, country_2) : " + con  )

   }
}

We have created two lists country_1 and country_2. We are concatenating two lists country_1 and country_2 into a single country list using ::: operator. In the second case we are using .::: operator to concat country_1 and country_2 into “cont” list and the second list country_2 data will be first inserted and then country_1 list data is displayed.

Finally we use concat method to concatenate country_1 and country_2 into the list “con”.

Run the above code by typing Country.main(null) and you will see below output.

 
country_1 ::: country_2 : List(India, SriLanka, Algeria, Austria, Belgium, Canada)
country_1.:::(country_2) : List(Austria, Belgium, Canada, India, SriLanka, Algeria)
List.concat(country_1, country_2) : List(India, SriLanka, Algeria, Austria, Belgium, Canada)

Scala Reverse List Order

The List data structure provides List.reverse method to reverse all elements of the list.

Consider an example below.


object Country {
	def main(args:Array[String]) {
	val country = List("Denmark","Sweden","France")
	println("Country List before reversal :" + country)
	println("Country List after reversal :" + country.reverse)
}
}

Here we are using reverse method to reverse the elements of the country list.

Run the code by typing Country.main(null) and you will see below output.


Country List before reversal :List(Denmark, Sweden, France)
Country List after reversal :List(France, Sweden, Denmark)

Scala Creating Uniform Lists

The List.fill() method creates zero or more copies of the same element.

Consider an example;


object Student {
   def main(args: Array[String]) {
      val name = List.fill(6)("Rehan") 
      println( "Name : " + name  )

      val id = List.fill(6)(12)         
      println( "Id : " + id  )
   }
}

Here we are using fill method and creating the name list with same name “Rehan” for six elements . The id list created with the same id 12 for all the six elements.


scala>Student.main(null)

Name : List(Rehan, Rehan, Rehan, Rehan, Rehan, Rehan)
Id : List(12, 12, 12, 12, 12, 12)

Scala List Methods

Some of the other methods supported by List are;

def distinct: List[X] → Builds a new list from the list without any duplicate elements.

def indexOf(elem: X, from: Int): Int → Finds index of first occurrence of some value in the list after or at some start index.

def length: Int → Returns the length of the list.

def sorted[Y >: X]: List[X] → Sorts the list according to an Ordering.

def sum: A → Sums up the elements of this collection.

def toString(): String → Converts the list to a string.

def min: A → Finds the smallest element.

def max A → Finds the largest element.

def lastIndexOf(elem: A, end: Int): Int → Finds index of last occurrence of some value in the list before or at a given end index.

def toMap[X, Y]: Map[X, Y] → Converts this list to a map.

Scala Set

Set is a collection of unique elements of the same type. Unlike list Set does not contain duplicate elements. Sets can be mutable or immutable. When the object is immutable the object itself cannot be changed.

Scala uses immutable set by default. Import scala.collection.mutable.Set to use the mutable set explicitly.

For example;


val country = Set("Russia", "Denmark", "Sweden")

Set of Integer data type can be created as


var id : Set[Int] = Set(4,5,6,7,8,9)

Empty Set can be created as;


var age = Set()

Basic Operation on Set in Scala

The basic operations include;

head → returns first element of a set.

tail → returns all the elements except the first element in the set.

isempty → returns true if the set is empty else returns false.

Consider an example;


object Student {
   def main(args: Array[String]) {
      val name = Set("Smith", "Brown", "Allen")
      val id: Set[Int] = Set()

      println( "Head of name : " + name.head )
      println( "Tail of name : " + name.tail )
      println( "Check if name is empty : " + name.isEmpty )
      println( "Check if id is empty : " + id.isEmpty )
   }
}

Here we are creating student object with two sets “names” and “id”. We are doing head, tail and empty operations on these arrays and printing the result.


scala>Student.main(null)

Head of name : Smith
Tail of name : Set(Brown, Allen)
Check if name is empty : false
Check if id is empty : true

Scala Concatenating Sets

To concatenate one or more sets use ++ operator or Set.++() method. While adding the sets duplicate items are removed.

For example;


object Furniture {
   def main(args: Array[String]) {
      val furniture_1 = Set("Sofa", "Table", "chair")
      val furniture_2 = Set("Bed", "Door")

       var furniture = furniture_1 ++ furniture_2
      println( "furniture_1 ++ furniture_2 : " + furniture )

      var furn = furniture_1.++(furniture_2)
      println( "furniture_1.++(furniture_2) : " + furn )
   }
}

We are creating two sets furniture_1 and furniture_2 and concatenating these two sets into furniture and furn using ++ and Set.++ operators.


scala> Furniture.main(null)

furniture_1 ++ furniture_2 : Set(Door, Sofa, Bed, Table, chair)
furniture_1.++(furniture_2) : Set(Door, Sofa, Bed, Table, chair)

Common Values in a Set

The Set.& method or Set.intersect method can be used to find the common elements in two or more sets.

Consider an example below.


object Numbers {
   def main(args: Array[String]) {
      val n1 = Set(11,45,67,78,89,86,90)
      val n2 = Set(10,20,45,67,34,78,98,89)

      println( "n1.&(n2) : " + n1.&(n2) )
      println( "n1.intersect(n2) : " + n1.intersect(n2) )
   }
}

We are creating two sets of numbers n1 and n2 and finding common elements present in both the sets.


scala> Numbers.main(null)

n1.&(n2) : Set(78, 89, 45, 67)
n1.intersect(n2) : Set(78, 89, 45, 67)

Maximum and Minimum elements in a Set

The Set.min method is used to find out the minimum and Set.max method to find out the maximum amongst the elements available in a set.

Consider an example;


object Numbers {
   def main(args: Array[String]) {
      val num1 = Set(125,45,678,34,20,322,10)

      println( "Minimum  element in the Set is : " + num1.min )
      println( "Maximum  element in the Set is : " + num1.max )
   }
}

We are finding the minimum and maximum numbers in set “num1” using the min and max methods.


scala> Numbers.main(null)

Minimum  element in the Set is : 10
Maximum  element in the Set is : 678

Other useful Scala Set Methods

Some of the Set methods in scala programming are;

def contains(elem: X): Boolean → Returns true if elem is contained in this set, else returns false.

def last: X → Returns the last element.

def product: X → Returns the product of all elements of this immutable set with respect to the * operator in num

def size: Int → Returns the number of elements in this immutable set.

def sum: X → Returns the sum of all elements of this immutable set with respect to the + operator in num.

def toList: List[X] → Returns a list containing all elements of this immutable set.

def toSeq: Seq[X] → Returns a sequence containing all elements of this immutable set.

def toArray: Array[X] → Returns an array containing all elements of this immutable set.

def subsetOf(that: Set[X]): Boolean → Returns true if this set is a subset of that, i.e. if every element of this set is also an element of that.

def mkString: String → Displays all elements of this immutable set in a string.

That’s all for now, we will look into other Scala Collection classes in coming posts.

Comments

  1. ravi says:

    Declare the list in the below fashion

    val SNames = List[String](“Rohan”, “Andreas”, “Rob”, “John”)

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages