Scala – Set

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

Learn About Sets in Scala Collections

 

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.

Sets are a fundamental data structure in Scala collections that represent a collection of unique elements with no duplicate values. In Scala, sets are immutable by default, meaning that once a set is created, its elements cannot be changed. Sets are implemented using hash tables, which provide efficient lookup, insertion, and deletion operations.

To create a set in Scala, you can use the Set object and specify the elements:

 

·        By default immutable

  They do not maintain order

·        Set can’t be access 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 = 

1Set

("Python", "DataScience", "Sql")

valnums: Set[Int] = 

Set

()

1println

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

println

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

2println

( "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 = 

1Set

("Python", "DataScience", "Sql")

vallang2 = 

Set

("Hadoop", "Scala","AWS")

// using two sets with ++ as operator

varlang = lang1 ++ lang2

1println

( "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

2println

( "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

eprintln

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

#println

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

  }
}

Learn About Sets in Scala Collections

Quick Support

image image