Scala Set (Collection)

Scala 集合Scala Collections

Scala Set is a collection of objects without duplicates; 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 referencescala.collection.mutable.Setthe package.

By default, scala.collection.immutable.Set is referenced. 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 mutable collections, you need to import scala.collection.mutable.Set:

Example

import scala.collection.mutable.Set // Can import mutable collection 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 Set and immutable Set have operations for adding or deleting elements, there is a very big difference. Operating on an immutable Set produces a new set, and the original set remains unchanged, just like List. Operating on a mutable Set, however, changes the Set itself, similar to ListBuffer.


Set Basic Operations

Scala collections have three basic operations:

  • headReturn the first element of the collection
  • tailReturn a collection containing all elements except the first
  • isEmptyReturn true when the collection is empty

Any operation on Scala collections can be expressed using these three basic operations. Example:

Example

object Test {
   def main(args: Array[String]) {
      val site = Set("Example", "Google", "Baidu")
      val nums: Set[Int] = Set()

      println( "The first website is : " + site.head )
      println( "The last website is : " + site.tail )
      println( "Check whether the list site is empty : " + site.isEmpty )
      println( "Check whether nums is empty : " + nums.isEmpty )
   }
}

Executing the above code produces the following output:

$ vim Test.scala 
$ scala Test.scala 
第一网站是 : Example
最后一个网站是 : Set(Google, Baidu)
查看列表 site 是否为空 : false
查看 nums 是否为空 : true

Concatenating Sets

You can use++operator orSet.++()method to concatenate two sets. If there are duplicate elements, they will be removed. Example:

Example

object Test {
   def main(args: Array[String]) {
      val site1 = Set("Example", "Google", "Baidu")
      val site2 = Set("Faceboook", "Taobao")

      // ++ used as operator
      var site = site1 ++ site2
      println( "site1 ++ site2 : " + site )

      // ++ used as method
      site = site1.++(site2)
      println( "site1.++(site2) : " + site )
   }
}

Executing the above code produces the following output:

$ vim Test.scala 
$ scala Test.scala 
site1 ++ site2 : Set(Faceboook, Taobao, Google, Baidu, Example)
site1.++(site2) : Set(Faceboook, Taobao, Google, Baidu, Example)

Finding the Largest and Smallest Elements in a Set

You can useSet.minmethod to find the smallest element in the set, useSet.maxmethod to find the largest element in the set. Example:

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 set
      println( "The minimum element in Set(5,6,9,20,30,45) is : " + num.min )
      println( "The maximum element in Set(5,6,9,20,30,45) is : " + num.max )
   }
}

Executing the above code produces the following output:

$ 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 useSet.&method orSet.intersectmethod to view the intersection elements of the two sets. Example:

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) )
   }
}

Executing the above code produces the following output:

$ 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 set and creates a new set, unless the element already exists

2

def -(elem: A): Set[A]

Removes elements from the set and creates a new set

3

def contains(elem: A): Boolean

Returns true if the element exists in the set, otherwise false.

4

def &(that: Set[A]): Set[A]

Returns the intersection of two sets

5

def &~(that: Set[A]): Set[A]

Returns the difference of two sets

6

def +(elem1: A, elem2: A, elems: A*): Set[A]

Creates a new immutable collection by adding elements from 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 collection by removing elements contained in the specified collection

9

def addString(b: StringBuilder): StringBuilder

Adds all elements of the immutable collection to a string buffer

10

def addString(b: StringBuilder, sep: String): StringBuilder

Adds all elements of the immutable collection to a string buffer, using the specified separator

11

def apply(elem: A)

Checks whether the collection contains the specified element

12

def count(p: (A) => Boolean): Int

Counts the number of collection elements that satisfy a specified condition

13

def copyToArray(xs: Array[A], start: Int, len: Int): Unit

Copies immutable collection elements to an array

14

def diff(that: Set[A]): Set[A]

Compares the difference of two sets

15

def drop(n: Int): Set[A]]

Returns a new collection with the first n elements discarded

16

def dropRight(n: Int): Set[A]

Returns a new collection with the last n elements discarded

17

def dropWhile(p: (A) => Boolean): Set[A]

Drops elements from left to right until condition p is false

18

def equals(that: Any): Boolean

The equals method can be used for any sequence. It is used to compare whether 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[A]

Outputs all elements of the immutable collection that meet the specified condition.

21

def find(p: (A) => Boolean): Option[A]

Finds the first element in the immutable collection that satisfies the specified condition

22

def forall(p: (A) => Boolean): Boolean

Finds whether the 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[A]

Returns all elements except the last

26

def intersect(that: Set[A]): Set[A]

Computes the intersection of two sets

27

def isEmpty: Boolean

Determines whether the collection 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

Finds 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 collection as a string using a separator

35

def product: A

Returns the product of the 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 the immutable collection into two containers: the first consists of the first n elements, and the second consists of the remaining elements

38

def subsetOf(that: Set[A]): Boolean

Returns true if the set 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 the 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 the 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 representation of the object

For more methods, please refer tothe API documentation

Scala 集合Scala Collections

Other Extensions