
- Scala Collections - Home
- Scala Collections - Overview
- Scala Collections - Environment Setup
- Scala Collections - Arrays
- Scala Collections - Array
- Scala Collections - Multi-Dimensional Array
- Scala Collections - Array using Range
- Scala Collections - ArrayBuffer
- Scala Collections - Lists
- Scala Collections - List
- Scala Collections - ListBuffer
- Scala Collections - ListSet
- Scala Collections - Vector
- Scala Collections - Sets
- Scala Collections - Set
- Scala Collections - BitSet
- Scala Collections - HashSet
- Scala Collections - TreeSet
- Scala Collections - Maps
- Scala Collections - Map
- Scala Collections - HashMap
- Scala Collections - ListMap
- Scala Collections - Miscellaneous
- Scala Collections - Iterator
- Scala Collections - Option
- Scala Collections - Queue
- Scala Collections - Tuple
- Scala Collections - Seq
- Scala Collections - Stack
- Scala Collections - Stream
- Scala Collections Combinator methods
- Scala Collections - drop
- Scala Collections - dropWhile
- Scala Collections - filter
- Scala Collections - find
- Scala Collections - flatMap
- Scala Collections - flatten
- Scala Collections - fold
- Scala Collections - foldLeft
- Scala Collections - foldRight
- Scala Collections - map
- Scala Collections - partition
- Scala Collections - reduce
- Scala Collections - scan
- Scala Collections - zip
- Scala Collections Useful Resources
- Scala Collections - Quick Guide
- Scala Collections - Useful Resources
- Scala Collections - Discussion
Scala Collections - HashSet
Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. HashSet implements immutable sets and uses hash table. Elements insertion order is not preserved.
Declaring HashSet Variables
The following is the syntax for declaring an HashSet variable.
Syntax
var z : HashSet[String] = HashSet("Zara","Nuha","Ayan")
Here, z is declared as an hash-set of Strings which has three members. Values can be added by using commands like the following −
Command
var myList1: HashSet[String] = myList + "Naira";
Processing HashSet
Below is an example program of showing how to create, initialize and process HashSet −
Example
import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { var mySet: HashSet[String] = HashSet("Zara","Nuha","Ayan"); // Add an element var mySet1: HashSet[String] = mySet + "Naira"; // Remove an element var mySet2: HashSet[String] = mySet - "Nuha"; // Create empty set var mySet3: HashSet[String] = HashSet.empty[String]; println(mySet); println(mySet1); println(mySet2); println(mySet3); } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
HashSet(Zara, Nuha, Ayan) HashSet(Zara, Nuha, Ayan, Naira) HashSet(Zara, Ayan) HashSet()
Checking Membership
You can check if a value is present in a HashSet using the contains method. This method returns true if the value is present and false otherwise.
Example
Try following example for checking membership whether these exist or not -
import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { var mySet: HashSet[String] = HashSet("Zara", "Nuha", "Ayan") // Check if the HashSet contains "Nuha" println(mySet.contains("Nuha")) // Check if the HashSet contains "Naira" println(mySet.contains("Naira")) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
true false
Common Set Operations
You can perform various common set operations such as union, intersection, and difference on HashSet. These operations are useful for comparing and combining sets.
- Union - For all unique elements from both sets.
- Intersection - For common unique elements from both sets.
- Difference - For elements from the first set that are not in the second set.
Example
Try following example for these set operations -
import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { val set1: HashSet[String] = HashSet("Zara", "Nuha", "Ayan") val set2: HashSet[String] = HashSet("Ayan", "Naira", "Maira") // Perform union operation val unionSet = set1 union set2 println("Union: " + unionSet) // Perform intersection operation val intersectionSet = set1 intersect set2 println("Intersection: " + intersectionSet) // Perform difference operation val differenceSet = set1 diff set2 println("Difference: " + differenceSet) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Union: HashSet(Zara, Nuha, Ayan, Naira, Maira) Intersection: HashSet(Ayan) Difference: HashSet(Zara, Nuha)
Finding Maximum and Minimum Elements
You can find the maximum and minimum elements in a HashSet using the max and min methods, respectively.
Example
Try following example for finding max and min elements in Hashset -
import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { val numbers: HashSet[Int] = HashSet(5, 2, 8, 1, 4) // Find the maximum element println("Max element: " + numbers.max) // Find the minimum element println("Min element: " + numbers.min) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Max element: 8 Min element: 1
Subset and Superset
You can check if one HashSet is a subset of another using the subsetOf method. Similarly, you can check if a set is a superset of another using the supersetOf method.
Example
Try following example for checking subset and superset in HashSet -
import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { val set1: HashSet[String] = HashSet("Zara", "Nuha") val set2: HashSet[String] = HashSet("Zara", "Nuha", "Ayan") // Check if set1 is a subset of set2 val isSubset = set1.subsetOf(set2) println("Is set1 a subset of set2? " + isSubset) // Check if set2 is a superset of set1 val isSuperset = set2.subsetOf(set1) println("Is set2 a superset of set1? " + isSuperset) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Is set1 a subset of set2? true Is set2 a superset of set1? false
Mutable HashSet
While HashSet in Scala is immutable by default, Scala also provides mutable versions of sets. Mutable sets allow in-place modification of elements.
Declaring Mutable HashSet
To use a mutable HashSet, you need to import scala.collection.mutable.HashSet.
Syntax
import scala.collection.mutable.HashSet var z: HashSet[String] = HashSet("Zara", "Nuha", "Ayan")
Example
import scala.collection.mutable.HashSet object Demo { def main(args: Array[String]) = { var mySet: HashSet[String] = HashSet("Zara", "Nuha", "Ayan") // Add an element to the mutable HashSet mySet += "Naira" // Remove an element from the mutable HashSet mySet -= "Nuha" // Print the modified HashSet println(mySet) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
HashSet(Zara, Ayan, Naira)
Transforming Elements
You can transform the elements of a HashSet using the map method. This method applies a function to each element of the set and returns a new set with the transformed elements.
Example
Try following example for doubling each element of HashSet -
import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { val numbers: HashSet[Int] = HashSet(1, 2, 3, 4, 5) // Transform the elements by doubling them val doubled = numbers.map(_ * 2) println(doubled) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
HashSet(2, 4, 6, 8, 10)
Filtering Elements
You can filter elements of a HashSet using the filter method. This method returns a new set containing only the elements that satisfy a given predicate.
Example
Try following example for filtering even numbers in HashSet -
import scala.collection.immutable.HashSet object Demo { def main(args: Array[String]) = { val numbers: HashSet[Int] = HashSet(1, 2, 3, 4, 5) // Filter elements that are even val evens = numbers.filter(_ % 2 == 0) println(evens) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
HashSet(2, 4)
Scala HashSet Summary
- HashSet in Scala is a collection of unique elements.
- HashSet is immutable by default, but mutable versions are also available.
- You can add, remove, and check for elements in a HashSet.
- Common set operations such as union, intersection, and difference can be performed on HashSet.
- You can find the maximum and minimum elements in a set.
- You can check for subset and superset relationships between sets.
- You can transform and filter elements in a HashSet.