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
- Scala Map
- Set in Scala | Set-2
- Scala | Either
- Scala | Arrays
- How to get all the keys from a Scala map
- Scala | Final
- Recursion in Scala
- StringBuilder in Scala
- Scala sum Map values
- Scala Map take() method with example
- Scala Lists
- Scala | map() method
- while and do while Loop in Scala
- How to get all the values from a Scala map
- Enumeration in Scala
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.