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.
// 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
- 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 as shown in the below example.
- 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.
// Immutable empty set val variable_name = Set() // Mutable empty set var variable_name = Set()
Set 1: Set(Geeks, GFG, GeeksforGeeks, Geek123) Set 2: Scala C# Ruby PHP C Java
Set 1: Set(Geeks, GFG, GeeksforGeeks, Geek123) Set 2: 10 100000 10000 1000 100
The empty set is: Set()
In Set, SortedSet is used to get values from the set in sorted order. SortedSet is only work for immutable set.
0 3 6 7 8 45 56 87