Set

A set is a collection of unique elements of the same type. Unlike list Set does not contain duplicate elements.You can apply various operations on them. It is defined in the Scala.collection.immutable package.
 
Some Important points in scala set
  • In Scala, both mutable and immutable sets are available. Mutable set is those set in which the value of the object is change but, in the immutable set, the value of the object is not changed itself.
  • By default set in Scala are immutable.
  • In Scala, the immutable set is defined under Scala.collection.immutable._ package and mutable set are defined under Scala.collection.mutable._ package.
  • We can also define a mutable set under Scala.collection.immutable._  package
  • A Set has various methods to add, remove clear, size, etc. to enhance the usage of the set.
  • In Scala, We are allowed to create empty set.
object demo {
def main(args : Array[String]){
val str1=Set("item1","item2","item3","item1")
println(str1)
}
}

Empty Set
object test{
def main(args: Array[String])
{
val emptySet=Set()
println("This is empty Set:")
println(emptySet)
}
}

Sorted Set
import scala.collection.immutable.SortedSet
object Demo
{
def main(args:Array[String])
{
val s1 = SortedSet(3, 7, 12, 9, 21)
s1.foreach(x => println(x))
}
}

import scala.collection.immutable.SortedSet
object Demo
{
def main(args:Array[String])
{
val s1 = SortedSet(1, 2, 3, 4, 5)
s1.foreach(x => println(x + " times " + x + " = " + x*x))
}
}






No comments:

Post a Comment