Scala Sets
[ Scala Collections](#)
A Scala Set is a collection of non-repeatable objects. All elements are unique.
Scala collections are divided into mutable and immutable collections.
By default, Scala uses immutable collections. If you want to use mutable collections, you need to import the **scala.collection.mutable.Set** package.
The default import is scala.collection.immutable.Set. An example of an immutable collection is as follows:
## Example
val set = Set(1,2,3)
println(set.getClass.getName)//
println(set.exists(_%2==0))//true
println(set.drop(1))//Set(2,3)
If you need to use a mutable collection, you need to import scala.collection.mutable.Set:
## Example
import scala.collection.mutable.Set// Mutable collections can be imported anywhere
val mutableSet = Set(1,2,3)
println(mutableSet.getClass.getName)// scala.collection.mutable.HashSet
mutableSet.add(4)
mutableSet.remove(1)
mutableSet +=5
mutableSet -=2
println(mutableSet)// Set(5, 3, 4)
val another = mutableSet.toSet
println(another.getClass.getName)// scala.collection.immutable.Set
> **Note:** Although both mutable and immutable Sets have operations to add or remove elements, there is a very big difference. Operating on an immutable Set will produce a new Set, and the original Set remains unchanged, which is the same as List. Operating on a mutable Set modifies the Set itself, similar to ListBuffer.
* * *
## Basic Operations on Collections
Scala collections have three basic operations:
* `head` returns the first element of the collection
* `tail` returns a collection consisting of all elements except the first
* `isEmpty` returns true if the collection is empty
Any operation on Scala collections can be expressed using these three basic operations. An example is as follows:
## Example
object Test {
def main(args: Array){
val site = Set("Tutorial", "Google", "Baidu")
val nums: Set= Set()
println("First website is : " + site.head)
println("Last website is : " + site.tail)
println("Check if list site is empty : " + site.isEmpty)
println("Check if nums is empty : " + nums.isEmpty)
}
}
Execute the above code, the output result is:
$ vim Test.scala $ scala Test.scala First website is : TutorialLast website is : Set(Google, Baidu)Check if list site is empty : falseCheck if nums is empty : true
* * *
## Concatenating Collections
You can use the **++** operator or the **Set.++()** method to concatenate two collections. If there are duplicate elements, the duplicates will be removed. An example is as follows:
## Example
object Test {
def main(args: Array){
val site1 = Set("Tutorial", "Google", "Baidu")
val site2 = Set("Faceboook", "Taobao")
// ++ used as an operator
var site = site1 ++ site2
println("site1 ++ site2 : " + site )
// ++ used as a method
site = site1.++(site2)
println("site1.++(site2) : " + site )
}
}
Execute the above code, the output result is:
$ vim Test.scala $ scala Test.scala site1 ++ site2 : Set(Faceboook, Taobao, Google, Baidu, Tutorial) site1.++(site2) : Set(Faceboook, Taobao, Google, Baidu, Tutorial)
* * *
## Finding the Maximum and Minimum Elements in a Collection
You can use the **Set.min** method to find the minimum element in a collection and the **Set.max** method to find the maximum element in a collection. An example is as follows:
## Example
object Test {
def main(args: Array){
val num = Set(5,6,9,20,30,45)
// Find the maximum and minimum elements in the collection
println("Minimum element in Set(5,6,9,20,30,45) is : " + num.min)
println("Maximum element in Set(5,6,9,20,30,45) is : " + num.max)
}
}
Execute the above code, the output result is:
$ vim Test.scala $ scala Test.scala Minimum element in Set(5,6,9,20,30,45) is : 5Maximum element in Set(5,6,9,20,30,45) is : 45
* * *
## Intersection
You can use the **Set.&** method or the **Set.intersect** method to find the intersection of two collections. An example is as follows:
## Example
object Test {
def main(args: Array){
val num1 = Set(5,6,9,20,30,45)
val num2 = Set(50,60,9,20,35,55)
// Intersection
println("num1.&(num2) : " + num1.&(num2))
println("num1.intersect(num2) : " + num1.intersect(num2))
}
}
Execute the above code, the output result is:
$ vim Test.scala $ scala Test.scala num1.&(num2) : Set(20, 9) num1.intersect(num2) : Set(20, 9)
* * *
## Common Methods of Scala Set
The following table lists the commonly used methods of Scala Set:
| No. | Method & Description |
| --- | --- |
| 1 | **def +(elem: A): Set** Adds a new element to the collection, x, and creates a new collection, unless the element already exists |
| 2 | **def -(elem: A): Set** Removes an element from the collection and creates a new collection |
| 3 | **def contains(elem: A): Boolean** Returns true if the element exists in the collection, otherwise returns false. |
| 4 | **def &(that: Set): Set** Returns the intersection of two collections |
| 5 | **def &~(that: Set): Set** Returns the difference of two collections |
| 6 | **def +(elem1: A, elem2: A, elems: A*): Set** Creates a new immutable collection by adding elements from the specified collection |
| 7 | **def ++(elems: A): Set** Merges two collections |
| 8 | **def -(elem1: A, elem2: A, elems: A*): Set** Creates a new immutable collection by removing elements from the specified collection |
| 9 | **def addString(b: StringBuilder): StringBuilder** Appends all elements of the immutable collection to the string builder |
| 10 | **def addString(b: StringBuilder, sep: String): StringBuilder** Appends all elements of the immutable collection to the string builder, using a specified separator |
| 11 | **def apply(elem: A)** Checks if the collection contains the specified element |
| 12 | **def count(p: (A) => Boolean): Int** Counts the number of elements in the collection that satisfy a specified condition |
| 13 | **def copyToArray(xs: Array, start: Int, len: Int): Unit** Copies elements of the immutable collection to an array |
| 14 | **def diff(that: Set): Set** Computes the difference of two collections |
| 15 | **def drop(n: Int): Set]** Returns a new collection discarding the first n elements |
| 16 | **def dropRight(n: Int): Set** Returns a new collection discarding the last n elements |
| 17 | **def dropWhile(p: (A) => Boolean): Set** Drops elements from left to right until condition p is not met |
| 18 | **def equals(that: Any): Boolean** The equals method can be used for any sequence. It is used to compare whether the sequences are equal. |
| 19 | **def exists(p: (A) => Boolean): Boolean** Determines whether an element satisfying the specified condition exists in the immutable collection. |
| 20 | **def filter(p: (A) => Boolean): Set** Outputs all elements of the immutable collection that satisfy the specified condition. |
| 21 | **def find(p: (A) => Boolean): Option** Finds the first element in the immutable collection that satisfies the specified condition |
| 22 | **def forall(p: (A) => Boolean): Boolean** Finds whether a specified condition applies to all elements of this collection |
| 23 | **def foreach(f: (A) => Unit): Unit** Applies a function to all elements of the immutable collection |
| 24 | **def head: A** Gets the first element of the immutable collection |
| 25 | **def init: Set** Returns all elements except the last one |
| 26 | **def intersect(that: Set): Set** Computes the intersection of two collections |
| 27 | **def isEmpty: Boolean** Checks if the collection is empty |
| 28 | **def iterator: Iterator** Creates a new iterator to iterate over the elements |
| 29 | **def last: A** Returns the last element |
| 30 | **def map(f: (A) => B): immutable.Set** Recalculates all elements using the given method |
| 31 | **def max: A** Finds the largest element |
| 32 | **def min
YouTip