English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Scala Set (collection) is a collection of objects without duplicates, and 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 reference scala.collection.mutable.Set Package.
The default reference is scala.collection.immutable.Set. Here is an example of an immutable collection:
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 mutable collections, you need to import scala.collection.mutable.Set:
import scala.collection.mutable.Set // Mutable collections can be introduced 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 significant difference. Operating on an immutable Set creates a new set, and the original set remains unchanged, similar to List. However, operating on a mutable Set changes the set itself, similar to ListBuffer.
Scala collections have three basic operations:
head returns the first element of the set
tail returns a set containing all elements except the first one
isEmpty returns true when the set is empty
Any operation on Scala collections can be expressed using these three basic operations. Example below:
object Test { def main(args: Array[String]) { val site = Set("w3codebox", "Google", "Baidu") val nums: Set[Int] = Set () println ("The first website is : " + site.head () println ("The last website is : " + site.tail () println ("Check if the list site is empty : " + site.isEmpty () println ("Check if nums is empty : " + nums.isEmpty () } }
Execute the above code, and the output result is:
$ vim Test.scala $ scala Test.scala The first website is : w3codebox The last website is : Set(Google, Baidu) Check if the list site is empty : false Check if nums is empty : true
You can use ++ Operator or Set.++()) Method to concatenate two sets. If there are duplicate elements, they will be removed. Example below:
object Test { def main(args: Array[String]) { val site1 = Set("w3codebox", "Google", "Baidu") val site2 = Set("Faceboook", "Taobao") // ++ As an operator var site = site1 ++ site2 println ("site1 ++ site2 : " + site ) // ++ As a method site = site1.++(site2) println ("site1.++(site2) : " + site ) } }
Execute the above code, and the output result is:
$ vim Test.scala $ scala Test.scala site1 ++ site2 : Set(Faceboook, Taobao, Google, Baidu, w3codebox) site1.++(site2) : Set(Faceboook, Taobao, Google, Baidu, w3codebox)
You can use Set.min Method to find the minimum element in the set, using Set.max Method to find the maximum element in the set. Example below:
object Test { def main(args: Array[String]) { val num = Set (5,6,9,20,30,45) // Find the maximum and minimum elements in the set println ("5,6,9,20,30,45) The minimum element in the set is : " + num.min () println ("5,6,9,20,30,45) The maximum element in the set is : " + num.max () } }
Execute the above code, and the output result is:
$ vim Test.scala $ scala Test.scala Set(5,6,9,20,30,45) The smallest element in the collection is : 5 Set(5,6,9,20,30,45) The largest element in the collection is : 45
You can use Set.& method or Set.intersect Methods to view the intersection elements of two collections. The following is an 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) ) } }
Execute the above code, and the output result is:
$ vim Test.scala $ scala Test.scala num1.&(num2) : Set(20, 9) num1.intersect(num2) : Set(20, 9)
The following table lists the commonly used methods of Scala Set:
Serial number | Methods and descriptions |
---|---|
1 | def +(elem: A): Set[A] Add a new element x to the collection and create a new collection, unless the element already exists |
2 | def -(elem: A): Set[A] Remove the element from the collection and create a new collection |
3 | def contains(elem: A): Boolean If the element exists in the collection, return true; otherwise, return false. |
4 | def &(that: Set[A]): Set[A] Return the intersection of the two collections |
5 | def &~(that: Set[A]): Set[A] Return the difference set of the two collections |
6 | def +(elem1: A, elem2: A, elems: A*: Set[A] Create a new immutable collection by adding the elements passed to the specified collection |
7 | def ++(elems: A): Set[A] Merge two collections |
8 | def -(elem1: A, elem2: A, elems: A*: Set[A] Create a new immutable collection by removing the elements passed to the specified collection |
9 | def addString(b: StringBuilder): StringBuilder Add all elements of the immutable collection to the string buffer |
10 | def addString(b: StringBuilder, sep: String): StringBuilder Add all elements of the immutable collection to the string buffer and use the specified separator |
11 | def apply(elem: A) Check if the collection contains the specified element |
12 | def count(p: (A) => Boolean): Int Calculate the number of elements in the collection that meet the specified conditions |
13 | def copyToArray(xs: Array[A], start: Int, len: Int): Unit Copy the elements of the immutable collection to an array |
14 | def diff(that: Set[A]): Set[A] Compare the difference set of two collections |
15 | def drop(n: Int): Set[A] Return a new collection that discards the first n elements |
16 | def dropRight(n: Int): Set[A] Return a new collection that discards the last n elements |
17 | def dropWhile(p: (A) => Boolean): Set[A] Discard elements from left to right until the condition p does not hold |
18 | def equals(that: Any): Boolean The equals method can be used for any sequence. It is used to compare whether the series are equal. |
19 | def exists(p: (A) => Boolean): Boolean Determine if the element that meets the specified condition exists in the immutable collection. |
20 | def filter(p: (A) => Boolean): Set[A] Output all elements of the immutable collection that meet the specified condition. |
21 | def find(p: (A) => Boolean): Option[A] Find the first element that meets the specified condition in the immutable collection |
22 | def forall(p: (A) => Boolean): Boolean Determine if the specified condition applies to all elements of this collection |
23 | def foreach(f: (A) => Unit): Unit Apply the function to all elements of the immutable collection |
24 | def head: A Get the first element of the immutable collection |
25 | def init: Set[A] Return all elements except the last one |
26 | def intersect(that: Set[A]): Set[A] Calculate the intersection of two collections |
27 | def isEmpty: Boolean Determine if the collection is empty |
28 | def iterator: Iterator[A] Create a new iterator to iterate over the elements |
29 | def last: A Return the last element |
30 | def map[B](f: (A) => B): immutable.Set[B] Recalculate all elements using the given method |
31 | def max: A Find the maximum element |
32 | def min: A Find the minimum element |
33 | def mkString: String Display all elements of the collection as a string |
34 | def mkString(sep: String): String Display all elements of the collection as a string using a delimiter |
35 | def product: A Returns the product of all numeric elements in the immutable collection |
36 | def size: Int Returns the number of elements in the immutable collection |
37 | def splitAt(n: Int): (Set[A], Set[A]) Splits an immutable collection into two containers, the first consisting of the first n elements, and the second consisting of the remaining elements |
38 | def subsetOf(that: Set[A]): Boolean Returns true if the collection contains a subset, otherwise returns false |
39 | def sum: A Returns the sum of all numeric elements in the immutable collection |
40 | def tail: Set[A] Returns all elements of an immutable collection 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 a collection to an array |
44 | def toBuffer[B >: A]: Buffer[B] Returns a buffer containing all elements of the immutable collection |
45 | def toList: List[A] Returns a List containing all elements of the immutable collection |
46 | def toMap[T, U]: Map[T, U] Returns a Map containing all elements of the immutable collection |
47 | def toSeq: Seq[A] Returns a Seq containing all elements of the immutable collection |
48 | def toString(): String Returns a string represented by an object |
More methods can be referred to API Documentation