Scala Set
Scala Set is a collection of objects with no duplicates; all elements are unique.
Scala collections are divided into mutable and immutable collections.
By default, Scala uses immutable sets; if you want to use a mutable set, you need to import scala.collection.mutable.Set the package.
scala.collection.immutable.Set is imported by default. An example of an immutable set 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)
To use a mutable set, you need to import scala.collection.mutable.Set:
Example
import
scala.
collection
.
mutable
.
Set
// the mutable set 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 big difference. Operating on an immutable Set produces a new set and leaves the original unchanged, just like List. Operating on a mutable Set changes the Set itself, similar to ListBuffer.
Basic Set Operations
Scala collections have three basic operations:
headReturns the first element of the collectiontailReturns a collection containing all elements except the firstisEmptyReturns true when the collection is empty
Any operation on a Scala collection can be expressed using these three basic operations. Example as follows:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
site
=
Set
(
"Runoob"
,
"Google"
,
"Baidu"
)
val
nums
:
Set
[
Int
]
=
Set
(
)
println
(
"The first website is: "
- site.
head
)
println
(
"The last website is: "
- site.
tail
)
println
(
"Check whether list site is empty: "
- site.
isEmpty
)
println
(
"Check whether nums is empty: "
- nums.
isEmpty
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
第一网站是 : Runoob
最后一个网站是 : Set(Google, Baidu)
查看列表 site 是否为空 : false
查看 nums 是否为空 : true
Concatenating Collections
You can use the ++ operator or the Set.++() method to concatenate two collections; if there are duplicate elements, they are removed. Example as follows:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
site1
=
Set
(
"Runoob"
,
"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
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
site1 ++ site2 : Set(Faceboook, Taobao, Google, Baidu, Runoob)
site1.++(site2) : Set(Faceboook, Taobao, Google, Baidu, Runoob)
Finding the Largest and Smallest Elements in a Collection
You can use the Set.min method to find the smallest element in a collection, and use the Set.max method to find the largest element. Example as follows:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
num
=
Set
(
5
,
6
,
9
,
20
,
30
,
45
)
// find the largest and smallest elements in the collection
println
(
"The smallest element in Set(5,6,9,20,30,45) is: "
- num.
min
)
println
(
"The largest element in Set(5,6,9,20,30,45) is: "
- num.
max
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
Set(5,6,9,20,30,45) 集合中的最小元素是 : 5
Set(5,6,9,20,30,45) 集合中的最大元素是 : 45
Intersection
You can use the Set.& The method or the Set.intersect method to view the intersection of two collections. Example as follows:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
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
)
)
}
}
The output of the code above is:
$ vim Test.scala
$ scala Test.scala
num1.&(num2) : Set(20, 9)
num1.intersect(num2) : Set(20, 9)
Scala Set Common Methods
The following table lists the commonly used methods of Scala Set:
| No. | Method and description |
|---|---|
| 1 |
def +(elem: A): Set[A] Adds a new element x to the collection and creates a new collection, unless the element already exists |
| 2 |
def -(elem: A): Set[A] 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, false otherwise. |
| 4 |
def &(that: Set[A]): Set[A] Returns the intersection of two collections |
| 5 |
def &~(that: Set[A]): Set[A] Returns the difference of two collections |
| 6 |
def +(elem1: A, elem2: A, elems: A*): Set[A] Creates a new immutable set by adding the elements of the specified collection |
| 7 |
def ++(elems: A): Set[A] Merges two collections |
| 8 |
def -(elem1: A, elem2: A, elems: A*): Set[A] Creates a new immutable set by removing the elements passed in the specified set |
| 9 |
def addString(b: StringBuilder): StringBuilder Adds all elements of the immutable set to a string buffer |
| 10 |
def addString(b: StringBuilder, sep: String): StringBuilder Adds all elements of the immutable set to a string buffer, using the specified separator |
| 11 |
def apply(elem: A) Tests whether the set contains the specified element |
| 12 |
def count(p: (A) => Boolean): Int Counts the number of set elements that satisfy the specified condition |
| 13 |
def copyToArray(xs: Array[A], start: Int, len: Int): Unit Copies the immutable set elements to an array |
| 14 |
def diff(that: Set[A]): Set[A] Computes the difference between two sets |
| 15 |
def drop(n: Int): Set[A]] Returns a new collection with the first n elements dropped |
| 16 |
def dropRight(n: Int): Set[A] Returns a new collection with the last n elements dropped |
| 17 |
def dropWhile(p: (A) => Boolean): Set[A] Drops elements from left to right until predicate p no longer holds |
| 18 |
def equals(that: Any): Boolean The equals method can be used on any sequence. It is used to compare whether two series are equal. |
| 19 |
def exists(p: (A) => Boolean): Boolean Determines whether an element satisfying the specified condition exists in the immutable set. |
| 20 |
def filter(p: (A) => Boolean): Set[A] Outputs all immutable set elements that meet the specified condition. |
| 21 |
def find(p: (A) => Boolean): Option[A] Finds the first element in the immutable set that satisfies the specified condition |
| 22 |
def forall(p: (A) => Boolean): Boolean Determines whether the specified condition applies to all elements of this set |
| 23 |
def foreach(f: (A) => Unit): Unit Applies a function to all elements of the immutable set |
| 24 |
def head: A Gets the first element of the immutable set |
| 25 |
def init: Set[A] Returns all elements except the last one |
| 26 |
def intersect(that: Set[A]): Set[A] Computes the intersection of two sets |
| 27 |
def isEmpty: Boolean Determines whether the set is empty |
| 28 |
def iterator: Iterator[A] Creates a new iterator to iterate over the elements |
| 29 |
def last: A returns the last element |
| 30 |
def map[B](f: (A) => B): immutable.Set[B] Recomputes all elements using the given method |
| 31 |
def max: A Finding the largest element |
| 32 |
def min: A Finds the smallest element |
| 33 |
def mkString: String Displays all elements of the collection as a string |
| 34 |
def mkString(sep: String): String Displays all elements of the set as a string using a separator |
| 35 |
def product: A Returns the product of the numeric elements in the immutable set. |
| 36 |
def size: Int Returns the number of elements in the immutable set |
| 37 |
def splitAt(n: Int): (Set[A], Set[A]) Splits the immutable set into two collections, the first consisting of the first n elements and the second of the remaining elements |
| 38 |
def subsetOf(that: Set[A]): Boolean Returns true if the set contains the subset, otherwise returns false |
| 39 |
def sum: A Returns the sum of all numeric elements in the immutable set |
| 40 |
def tail: Set[A] Returns all elements of an immutable set except the first element |
| 41 |
def take(n: Int): Set[A] Returns the first n elements |
| 42 |
def takeRight(n: Int):Set[A] Returns the last n elements |
| 43 |
def toArray: Array[A] Converts the set to an array |
| 44 |
def toBuffer[B >: A]: Buffer[B] Returns a buffer containing all elements of the immutable set |
| 45 |
def toList: List[A] Returns a List containing all elements of the immutable set |
| 46 |
def toMap[T, U]: Map[T, U] Returns a Map containing all elements of the immutable set |
| 47 |
def toSeq: Seq[A] Returns a Seq containing all elements of the immutable set |
| 48 |
def toString(): String Returns a string representing the object |
For more methods, refer to API Documentation
Scala Collections