A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request.
Syntax:
// Immutable set
val variable_name: Set[type] = Set(item1, item2, item3)
or
val variable_name = Set(item1, item2, item3)
// Mutable Set
var variable_name: Set[type] = Set(item1, item2, item3)
or
var variable_name = Set(item1, item2, item3)
Some Important Points about Set in Scala
Example 1:
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
val myset1: Set[String] = Set("Geeks", "GFG",
"GeeksforGeeks", "Geek123")
val myset2 = Set("C", "C#", "Java", "Scala",
"PHP", "Ruby")
println("Set 1:")
println(myset1)
println("\nSet 2:")
for(myset<-myset2)
{
println(myset)
}
}
}
|
Output:
Set 1:
Set(Geeks, GFG, GeeksforGeeks, Geek123)
Set 2:
Scala
C#
Ruby
PHP
C
Java
Example 2:
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
var myset1: Set[String] = Set("Geeks", "GFG",
"GeeksforGeeks", "Geek123")
var myset2 = Set(10, 100, 1000, 10000, 100000)
println("Set 1:")
println(myset1)
println("\nSet 2:")
myset2.foreach((item:Int)=>println(item))
}
}
|
Output:
Set 1:
Set(Geeks, GFG, GeeksforGeeks, Geek123)
Set 2:
10
100000
10000
1000
100
Example 3:
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
val myset = Set()
println("The empty set is:")
println(myset)
}
}
|
Output:
The empty set is:
Set()
Sorted Set
In Set, SortedSet is used to get values from the set in sorted order. SortedSet is only work for immutable set.
Example:
import scala.collection.immutable.SortedSet
object Main
{
def main(args: Array[String])
{
val myset: SortedSet[Int] = SortedSet(87, 0, 3, 45, 7, 56, 8,6)
myset.foreach((items: Int)=> println(items))
}
}
|
Output:
0
3
6
7
8
45
56
87
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Feb, 2019
Like Article
Save Article