Friday 20 May 2016

Scala Useful Code Snippets for Beginners(Part-5): Set

Introduction

In Scala, Set is a collection of elements. It does not allow duplicates and also no guarantee about the order the elements.

It has the following 3 flavours in Scala API
  1. scala.collection.Set
  2. scala.collection.mutable.Set
  3. scala.collection.immutable.Set
Based on context, we can use either Mutable or Immutable Set.

Just like Strings uses '+' operator for String concatenation,  Set uses '++' function (Not Operator) to concatenate two Sets. Set uses '+' function (Not Operator) to add an element to an existing Set.

NOTE:- If we don't specify the type of Set, Scala Compiler creates Immutable Set automatically.

Let us explore Scala Set with some examples.

Examples:

To create empty Set

scala> val set1 = Set()
set1: scala.collection.immutable.Set[Nothing] = Set()

NOTE:- By default, it creates Immutable Set

To Concatenate Two Sets using "++"

scala> val set2 = Set(1,2,3,4)
set2: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)

scala> val set3 = Set(4,5,6)
set3: scala.collection.immutable.Set[Int] = Set(4, 5, 6)

scala> val set4 = set2 ++ set3

set4: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)

NOTE:- As Set does not supports duplicates, It adds "4" only once.

NOTE:- Set does not guarantee the order of the elements.

To know whether an element exists in a Set or not

scala> set4
res0: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)

scala> set4(0)
res1: Boolean = false

scala> set4(1)

res2: Boolean = true


NOTE:- As Set does not support index of elements, we cannot access it's elements using index.

NOTE:- Set index starts with zero.

To reverse the Set elements

scala> set4.reverse
<console>:14: error: value reverse is not a member of scala.collection.immutable.Set[Int]
       set4.reverse
            ^
NOTE:- As Set does not guarantee the order of the elements, it does support 'reverse' function.

To get head and tail of a Set

scala> set4
res0: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 3, 4)

scala> set4.head
res4: Int = 5

NOTE:- 'head' function returns first or head element of the Set ( It's same for any collection API like List, Seq, Map etc.).

scala> set4.tail
res5: scala.collection.immutable.Set[Int] = Set(1, 6, 2, 3, 4)

NOTE:- 'tail' function returns all elements of the Set  except first element (head element) ( It's same for any collection API like List, Seq, Map etc.).

To add one element to an existing Set

scala> val set5  = set4 + (7)

set5: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 7, 3, 4)

NOTE:- As set4 is val type, we cannot reassign new Set to it and also set4 is Immutable, we cannot change it. We should create a new Set as shown above.

It does not guarantee whether it adds at first or last or middle. I can happen at any place.

Thank you for reading my posts. 
Please drop me your valuable suggestions or comments.

No comments:

Post a Comment