Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

HashSet In Scala

A HashSet is a collection of unique elements, and Scala provides both mutable and immutable versions of it. Unlike List or Array, a HashSet does not maintain elements in any specific order. It provides constant-time average performance for the basic operations (add, contains, and remove).

Immutable HashSet

By default, when you refer to a HashSet in Scala, you're using the immutable version. Once an immutable HashSet is created, it cannot be changed. Any operation that seems to "modify" it actually returns a new HashSet.

Importing and Creating:

import scala.collection.immutable.HashSet

val set = HashSet(1, 2, 3, 4)

Adding and Removing Elements:

Remember, these operations don't modify the original set but return a new one:

val newSet = set + 5      // HashSet(1, 2, 3, 4, 5)
val reducedSet = set - 3  // HashSet(1, 2, 4)

Mutable HashSet

If you need to modify a HashSet in place, you'd use the mutable version from the scala.collection.mutable package.

Importing and Creating:

import scala.collection.mutable.HashSet

val mutableSet = HashSet(1, 2, 3)

Modifying:

You can modify the set in-place:

mutableSet += 4   // Adds 4 to the set
mutableSet -= 2   // Removes 2 from the set

Other Common Operations:

  • Check if an element exists: mutableSet.contains(3)

  • Clearing all elements: mutableSet.clear()

Common Operations for Both Mutable and Immutable:

  • Union of two sets:

    val set1 = HashSet(1, 2, 3)
    val set2 = HashSet(3, 4, 5)
    val unionSet = set1 union set2  // Alternatively: set1 | set2
    
  • Intersection of two sets:

    val intersectSet = set1 intersect set2  // Alternatively: set1 & set2
    
  • Difference between two sets:

    val diffSet = set1 diff set2  // Elements in set1 but not in set2
    
  • Iterating over a HashSet:

    for (element <- set) {
      println(element)
    }
    
  • Size of the HashSet: set.size

Conclusion:

The choice between mutable and immutable HashSet depends on your use case. While the immutable version is typically preferred in a functional programming context because of its safety in concurrent scenarios and predictability, there are situations where the mutable version may be more performant or appropriate.

  1. Creating and initializing HashSet in Scala:

    • Description: HashSet can be created and initialized using the HashSet companion object or through mutable and immutable variations.
    • Code Example:
      // Immutable HashSet
      val immutableSet = Set(1, 2, 3)
      
      // Mutable HashSet
      import scala.collection.mutable.HashSet
      val mutableSet = HashSet("a", "b", "c")
      
  2. Mutable and immutable HashSet in Scala:

    • Description: Immutable HashSets cannot be modified after creation, while mutable HashSets support dynamic changes.
    • Code Example:
      // Immutable HashSet
      val immutableSet = Set(1, 2, 3)
      
      // Mutable HashSet
      import scala.collection.mutable.HashSet
      val mutableSet = HashSet("a", "b", "c")
      
  3. HashSet operations and methods in Scala:

    • Description: HashSets support various operations like +, -, ++, --, and more for modification.
    • Code Example:
      val set = Set(1, 2, 3)
      val updatedSet = set + 4
      
  4. Adding and removing elements from HashSet in Scala:

    • Description: Elements can be added using + and removed using - operations.
    • Code Example:
      val set = Set(1, 2, 3)
      val updatedSet = set + 4
      val removedSet = updatedSet - 2
      
  5. Accessing values in Scala HashSet:

    • Description: Values in HashSets can be accessed directly.
    • Code Example:
      val set = Set(1, 2, 3)
      val containsTwo = set.contains(2)
      
  6. Iterating over HashSet in Scala:

    • Description: HashSets can be iterated using foreach, for, or other iteration methods.
    • Code Example:
      val set = Set(1, 2, 3)
      set.foreach { value =>
        println(s"Value: $value")
      }
      
  7. Updating values in Scala HashSet:

    • Description: Values in HashSets can be updated using the + operation with an existing value.
    • Code Example:
      val set = Set(1, 2, 3)
      val updatedSet = set + 2 // Updating value to 2
      
  8. Scala HashSet vs. other collection types:

    • Description: HashSets provide fast membership checks, but other collection types may be preferred based on specific use cases.
    • Code Example:
      val list = List(1, 2, 3)
      val map = Map("a" -> 1, "b" -> 2)
      
  9. Pattern matching with HashSet in Scala:

    • Description: Pattern matching can be used to check for membership or extract values from HashSets.
    • Code Example:
      val set = Set(1, 2, 3)
      set.foreach {
        case value if value % 2 == 0 => println(s"Even value: $value")
        case _ => // Handle other cases
      }
      
  10. Default values and options in Scala HashSet:

    • Description: Default values or contains with Option can handle non-existing values in HashSets.
    • Code Example:
      val set = Set(1, 2, 3)
      val containsFour = set.contains(4) // Check for existence
      val valueOption = set.find(_ == 2) // Using Option
      
  11. Scala HashSet with case classes:

    • Description: HashSets can be used effectively with case classes for structured data storage.
    • Code Example:
      case class Person(name: String, age: Int)
      
      val personSet = Set(Person("Alice", 25), Person("Bob", 30))