Sets

A set is one of the most widely used collections. In sets order will not be preserved and sets don't allow duplicate elements. You can think of it as the mathematical notation of sets. Let's demonstrate this by an example, and we will see how sets don't preserve ordering and don't allow duplicates:

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

The following source code shows the different uses of sets in a Scala program:

package com.chapter4.CollectionAPI
object SetExample {
def main(args: Array[String]) {
// Empty set of integer type
var sInteger : Set[Int] = Set()
// Set of even numbers
var sEven : Set[Int] = Set(2,4,8,10)
//Or you can use this syntax
var sEven2 = Set(2,4,8,10)
val cities = Set("Dublin", "London", "NY")
val tempNums: Set[Int] = Set()
//Finding Head, Tail, and checking if the sets are empty
println( "Head of cities : " + cities.head )
println( "Tail of cities : " + cities.tail )
println( "Check if cities is empty : " + cities.isEmpty )
println( "Check if tempNums is empty : " + tempNums.isEmpty )
val citiesEurope = Set("Dublin", "London", "NY")
val citiesTurkey = Set("Istanbul", "Ankara")
// Sets Concatenation using ++ operator
var citiesConcatenated = citiesEurope ++ citiesTurkey
println( "citiesEurope ++ citiesTurkey : " + citiesConcatenated )
//Also you can use ++ as a method
citiesConcatenated = citiesEurope.++(citiesTurkey)
println( "citiesEurope.++(citiesTurkey) : " + citiesConcatenated )
//Finding minimum and maximum elements in the set
val evenNumbers = Set(2,4,6,8)
// Using the min and max methods
println( "Minimum element in Set(2,4,6,8) : " + evenNumbers.min )
println( "Maximum element in Set(2,4,6,8) : " + evenNumbers.max )
}
}

You will get the following output:

Head of cities : Dublin
Tail of cities : Set(London, NY)
Check if cities is empty : false
Check if tempNums is empty : true
citiesEurope ++ citiesTurkey : Set(London, Dublin, Ankara, Istanbul, NY)
citiesEurope.++(citiesTurkey) : Set(London, Dublin, Ankara, Istanbul, NY)
Minimum element in Set(2,4,6,8) : 2
Maximum element in Set(2,4,6,8) : 8

From my personal experience while developing Spark applications using Java or Scala, I found very frequent uses of tuples, especially for grouping collections of elements without using any explicit classes. In the next subsection, we will see how to get started with Tuples in Scala.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.205.2