📅  最后修改于: 2023-12-03 14:47:14.968000             🧑  作者: Mango
In Scala, HashSet
is an unordered collection of unique elements. It is a mutable data structure belonging to the scala.collection.mutable package. This collection provides fast retrieval of elements and efficient addition and removal of elements.
To create a HashSet in Scala, you need to import the necessary package as shown below:
import scala.collection.mutable.HashSet
Once imported, you can create an empty HashSet or initialize it with some elements:
// Empty HashSet
val emptySet = HashSet()
// HashSet initialized with elements
val colorSet = HashSet("Red", "Green", "Blue")
You can add elements to a HashSet using the +=
or add
methods:
colorSet += "Yellow"
colorSet.add("Orange")
Elements can be removed from a HashSet using the -=
or remove
methods:
colorSet -= "Green"
colorSet.remove("Blue")
You can check if an element exists in a HashSet using the contains
method:
val containsRed = colorSet.contains("Red")
To iterate over the elements of a HashSet, you can use the foreach
method or perform other collection operations like map
, filter
, etc.:
colorSet.foreach(println)
To perform a union operation on two HashSets, you can use the union
method:
val set1 = HashSet(1, 2, 3)
val set2 = HashSet(3, 4, 5)
val unionSet = set1.union(set2)
To find the common elements between two HashSets, you can use the intersect
method:
val intersectSet = set1.intersect(set2)
To find the elements that are present in one HashSet but not in another, you can use the diff
method:
val diffSet = set1.diff(set2)
In conclusion, Scala HashSet provides a convenient and efficient way to store unique elements. It offers various operations for adding, removing, and manipulating elements with constant time complexity. Its versatility makes it a valuable collection for many programming tasks.