Scala - Sets

Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. There are two kinds of Sets, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed.
By default, Scala uses the immutable Set. If you want to use the mutable Set, you'll have to import scala.collection.mutable.Set class explicitly. If you want to use both mutable and immutable sets in the same collection, then you can continue to refer to the immutable Set as Set but you can refer to the mutable Set as mutable.Set.
Here is how you can declare immutable Sets −
// Empty set of integer type
var s : Set[Int] = Set()

// Set of integer type
var s : Set[Int] = Set(1,3,5,7)

or 

var s = Set(1,3,5,7)

While defining an empty set, the type annotation is necessary as the system needs to assign a concrete type to variable.
All operations on sets can be expressed in terms of the following three methods −
head
This method returns the first element of a set.
tail
This method returns a set consisting of all elements except the first.
isEmpty
This method returns true if the set is empty otherwise false.
Try the following example showing usage of the basic operational methods −
object Demo {
   def main(args: Array[String]) {
      val fruit = Set("apples", "oranges", "pears")
      val nums: Set[Int] = Set()

      println( "Head of fruit : " + fruit.head )
      println( "Tail of fruit : " + fruit.tail )
      println( "Check if fruit is empty : " + fruit.isEmpty )
      println( "Check if nums is empty : " + nums.isEmpty )
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

Head of fruit : apples
Tail of fruit : Set(oranges, pears)
Check if fruit is empty : false
Check if nums is empty : true

You can use either ++ operator or Set.++() method to concatenate two or more sets, but while adding sets it will remove duplicate elements.
The Following is the example to concatenate two sets.
object Demo {
   def main(args: Array[String]) {
      val fruit1 = Set("apples", "oranges", "pears")
      val fruit2 = Set("mangoes", "banana")

      // use two or more sets with ++ as operator
      var fruit = fruit1 ++ fruit2
      println( "fruit1 ++ fruit2 : " + fruit )

      // use two sets with ++ as method
      fruit = fruit1.++(fruit2)
      println( "fruit1.++(fruit2) : " + fruit )
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

fruit1 ++ fruit2 : Set(banana, apples, mangoes, pears, oranges)
fruit1.++(fruit2) : Set(banana, apples, mangoes, pears, oranges)

You can use Set.min method to find out the minimum and Set.max method to find out the maximum of the elements available in a set. Following is the example to show the program.
object Demo {
   def main(args: Array[String]) {
      val num = Set(5,6,9,20,30,45)

      // find min and max of the elements
      println( "Min element in Set(5,6,9,20,30,45) : " + num.min )
      println( "Max element in Set(5,6,9,20,30,45) : " + num.max )
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

Min element in Set(5,6,9,20,30,45) : 5
Max element in Set(5,6,9,20,30,45) : 45

You can use either Set.& method or Set.intersect method to find out the common values between two sets. Try the following example to show the usage.
object Demo {
   def main(args: Array[String]) {
      val num1 = Set(5,6,9,20,30,45)
      val num2 = Set(50,60,9,20,35,55)

      // find common elements between two sets
      println( "num1.&(num2) : " + num1.&(num2) )
      println( "num1.intersect(num2) : " + num1.intersect(num2) )
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

num1.&(num2) : Set(20, 9)
num1.intersect(num2) : Set(20, 9)

Following are the important methods which you can use while playing with Sets. For a complete list of methods available, please check official documentation of Scala.
def +(elem: A): Set[A]
Creates a new set with an additional element, unless the element is already present.
def -(elem: A): Set[A]
Creates a new set with a given element removed from this set.
def contains(elem: A): Boolean
Returns true if elem is contained in this set, false otherwise.
def &(that: Set[A]): Set[A]
Returns a new set consisting of all elements that are both in this set and in the given set.
def &~(that: Set[A]): Set[A]
Returns the difference of this set and another set.
def +(elem1: A, elem2: A, elems: A*): Set[A]
Creates a new immutable set with additional elements from the passed sets
def ++(elems: A): Set[A]
Concatenates this immutable set with the elements of another collection to this immutable set.
def -(elem1: A, elem2: A, elems: A*): Set[A]
Returns a new immutable set that contains all elements of the current immutable set except one less occurrence of each of the given argument elements.
def addString(b: StringBuilder): StringBuilder
Appends all elements of this immutable set to a string builder.
def addString(b: StringBuilder, sep: String): StringBuilder
Appends all elements of this immutable set to a string builder using a separator string.
def apply(elem: A)
Tests if some element is contained in this set.
def count(p: (A) => Boolean): Int
Counts the number of elements in the immutable set which satisfy a predicate.
def copyToArray(xs: Array[A], start: Int, len: Int): Unit
Copies elements of this immutable set to an array.
def diff(that: Set[A]): Set[A]
Computes the difference of this set and another set.
def drop(n: Int): Set[A]]
Returns all elements except first n ones.
def dropRight(n: Int): Set[A]
Returns all elements except last n ones.
def dropWhile(p: (A) => Boolean): Set[A]
Drops longest prefix of elements that satisfy a predicate.
def equals(that: Any): Boolean
The equals method for arbitrary sequences. Compares this sequence to some other object.
def exists(p: (A) => Boolean): Boolean
Tests whether a predicate holds for some of the elements of this immutable set.
def filter(p: (A) => Boolean): Set[A]
Returns all elements of this immutable set which satisfy a predicate.
def find(p: (A) => Boolean): Option[A]
Finds the first element of the immutable set satisfying a predicate, if any.
def forall(p: (A) => Boolean): Boolean
Tests whether a predicate holds for all elements of this immutable set.
def foreach(f: (A) => Unit): Unit
Applies a function f to all elements of this immutable set.
def head: A
Returns the first element of this immutable set.
def init: Set[A]
Returns all elements except the last.
def intersect(that: Set[A]): Set[A]
Computes the intersection between this set and another set.
def isEmpty: Boolean
Tests if this set is empty.
def iterator: Iterator[A]
Creates a new iterator over all elements contained in the iterable object.
def last: A
Returns the last element.
def map[B](f: (A) => B): immutable.Set[B]
Builds a new collection by applying a function to all elements of this immutable set.
def max: A
Finds the largest element.
def min: A
Finds the smallest element.
def mkString: String
Displays all elements of this immutable set in a string.
def mkString(sep: String): String
Displays all elements of this immutable set in a string using a separator string.
def product: A
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 splitAt(n: Int): (Set[A], Set[A])
Returns a pair of immutable sets consisting of the first n elements of this immutable set, and the other elements.
def subsetOf(that: Set[A]): 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 sum: A
Returns the sum of all elements of this immutable set with respect to the + operator in num.
def tail: Set[A]
Returns a immutable set consisting of all elements of this immutable set except the first one.
def take(n: Int): Set[A]
Returns first n elements.
def takeRight(n: Int):Set[A]
Returns last n elements.
def toArray: Array[A]
Returns an array containing all elements of this immutable set.
def toBuffer[B >: A]: Buffer[B]
Returns a buffer containing all elements of this immutable set.
def toList: List[A]
Returns a list containing all elements of this immutable set.
def toMap[T, U]: Map[T, U]
Converts this immutable set to a map
def toSeq: Seq[A]
Returns a seq containing all elements of this immutable set.
def toString(): String
Returns a String representation of the object.