Scala – Set

  • date 8th October, 2020 |
  • by Prwatech |
  • 0 Comments

Set:

They are Iterables that contain no duplicate elements. The operations on sets are summarized in the following table for general sets and in the table after that for mutable sets.

·        By default immutable

·        They do not maintain order

·        Set can’t be accessed by their Index.

·        No Duplicity and Intersection & Union is simple

1. Example program to show usage of the basic set operational methods:

package Collection

object Set1 {

defmain(args: Array[String]) {

vallang1 = Set("Python", "DataScience", "Sql")

valnums: Set[Int] = Set()

println( "Best of Programming Language : " + lang1.head )

println( "Other Programming Language : " + lang1.tail )

println( "Check if Set is empty : " + lang1.isEmpty )

println( "Check if nums is empty : " + nums.isEmpty )

  }

}

2. Example program to show usage of the set with respect to concatenation:

package Collection

object Set2 {

defmain(args: Array[String]) {

vallang1 = Set("Python", "DataScience", "Sql")

vallang2 = Set("Hadoop", "Scala","AWS")

// using two sets with ++ as operator

varlang = lang1 ++ lang2

println( "lang1 ++ lang2 : " + lang )

// using two sets with ++ as method

lang = lang1.++(lang2)

println( "lang1.++(lang2) : " + lang )
  }
}

3. Example program to show usage of the set to find minimum and maximum of the elements available in a set and find common elements between two sets :

package Collection

object Set3 {

defmain(args: Array[String]) {

valnum1 = Set(1,6,13,21,32,47)

valnum2 = Set(21,62,9,32,38,57)

// min and max of the elements

println( "Min element in Set(1,6,13,21,32,47) : " + num1.min )

println( "Max element in Set(1,6,13,21,32,47) : " + num1.max )

// to find common elements between two sets

println( "num1.&(num2) : " + num1.&(num2) )

println( "num1.intersect(num2) : " + num1.intersect(num2) )

  }
}

Quick Support

image image