Scala Set


Release date:2023-11-18 Update date:2023-11-21 Editor:admin View counts:309

Label:

Scala Set

Scala set (collection) is a collection of objects without repetition, and all elements are unique.

Scala collections are divided into mutable and immutable collections.

By default, Scala uses immutable collections, and if you want to use mutablecollections, you need to refer to scala.collection.mutable.Set Bag.

Default reference 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 variable collection, you need to introduce scala.collection.mutable.Set :

Example

import scala.collection.mutable.Set // Variable sets 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 variable set and immutable. set has operations to add or remove elements, but there is a very big difference. Yes, immutable. set to perform the operation, a new set original set hasn’t changed, which has something to do with List same thing. While for variable, set to operate, the change is that the set in itself, with ListBuffer similar.

Basic operation of collection

The Scala collection has three basic operations:

  • head returns the first element of the collection

  • tail returns a collection containing elements other than the first element

  • isEmpty returns when the collection is empty true

Any operation on the Scala collection can be expressed using these three basic operations. Examples are 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 if the list site is empty : " + site.isEmpty )
      println( "Check if nums is empty : " + nums.isEmpty )
   }
}

Execute the above code, and the output is as follows:

$ vim Test.scala
$ scala Test.scala
The first website is : Runoob
The last website is : Set(Google, Baidu)
Check if the list site is empty : false
Check if nums is empty : true

Connection set

You can use it. ++ operator or Set.++() method to connect two collections. If there is a duplicate element, the duplicate element will be removed. Examples are 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 an method
      site = site1.++(site2)
      println( "site1.++(site2) : " + site )
   }
}

Execute the above code, and the output is as follows:

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

Find the largest and smallest elements in the collection

You can use it. Set.min method to find the smallest element in the collection, using the Set.max method to find the largest element in thecollection. Examples are 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 a set
      println( "Set(5,6,9,20,30,45) the smallest element is : " + num.min )
      println( "Set(5,6,9,20,30,45) the smallest element is : " + num.max )
   }
}

Execute the above code, and the output is as follows:

$ vim Test.scala
$ scala Test.scala
Set(5,6,9,20,30,45) the smallest element is : 5
Set(5,6,9,20,30,45) the smallest element is : 45

Intersection

You can use it. Set.& method or Set.intersect method to view the intersection elements of two collections. Examples are 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) )
   }
}

Execute the above code, and the output is as follows:

$ 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 Scala Set common methods:

Serial number

Method and description

1

Def + (elem: a): Set [A]

Add a new element to the collection, x, and create a new collection unless the element already exists

2

Def-(elem: a): Set [A]

Remove elements from the collection and create 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 sets

5

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

Returns the difference between two sets

6

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

Create a new immutable collection by adding elements passed in to the specified collection

7

Def + + (elems: a): Set [A]

Merge two sets

8

Def-(elem1: a, elem2: a, elems: A*): Set [A]

Creates a new immutable collection by removing elements passed into 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

Adds all elements of the immutable collection to the string buffer and uses the specified delimiter

11

Def apply (elem: a)

Detects whether the collection contains the specified element

12

Def count (p: (a) = > Boolean): Int

Calculate the number of set elements that meet the specified conditions

13

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

Copy immutable collection elements to an array

14

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

Compare the difference between two sets

15

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

Returns a new collection of the first n elements discarded

16

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

Returns a new collection of discarded last n elements

17

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

Discard elements from left to right until condition p is not true

18

Def equals (that: Any): Boolean

The equals method can be used for any sequence. Used to compare whether the series are equal.

19

Def exists (p: (a) = > Boolean): Boolean

Determines whether the element of the specified condition exists in the immutable set.

20

Def filter (p: (a) = > Boolean): Set [A]

Outputs all immutable collection elements that meet the specified criteria.

21

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

Find the first element in an immutable set that meets 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

Apply a function to all elements of an immutable set

24

Def head: A

Get the first element of an immutable set

25

Def init: Set [A]

Returns all elements except the last one

26

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

Calculate the intersection of two sets

27

Def isEmpty: Boolean

Determine whether the collection is empty

28

Def iterator: Iterator [A]

Create a new iterator to iterate over the element

29

Def last: A

Returns the last element

30

Def map [B] (F: (a) = > B): immutable.Set [B]

Recalculate all elements by a given method

31

Def max: A

Find the largest element

32

Def min: A

Find the smallest element

33

Def mkString: String

All elements of the collection are displayed as strings

34

Def mkString (sep: String): String

Use delimiters to display all elements of the collection as strings

35

Def product: A

Returns the product of numeric elements in an immutable set.

36

Def size: Int

Returns the number of immutable collection elements

37

Def splitAt (n: Int): (Set [A] , Set [A] )

Split the immutable set 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, false otherwise

39

Def sum: A

Returns the sum of all numeric elements in an immutable set

40

Def tail: Set [A]

Returns elements other than the first element in an immutable set

41

Def take (n: Int): Set [A]

Return the first n elements

42

Def takeRight (n: Int): Set [A]

Return the last n elements

43

Def toArray: Array [A]

Convert a collection to an array

44

Def toBuffer [B >: A] : Buffer [B]

Returns the buffer containing all the elements of the immutable set

45

Def toList: List [A]

Returns List, which contains all the elements of the immutable set

46

Def toMap [T, U] : Map [T, U]

Returns Map, which contains all the elements of the immutable set

47

Def toSeq: Seq [A]

Returns Seq, which contains all the elements of the immutable set

48

Def toString (): String

Returns a string represented by an object

For more methods, please refer to the API documentation

Powered by TorCMS (https://github.com/bukun/TorCMS).