w3resource

Scala set: Creating sets and finding the difference between two sets

Scala Set Exercise-4 with Solution

Write a Scala program to create a set and find the difference between two sets.

Sample Solution:

Scala Code:

object SetDifferenceExample {
  def main(args: Array[String]): Unit = {
    // Create two sets
    val set1 = Set(1, 2, 3, 4)
    val set2 = Set(3, 4, 5, 6)

   // Print the set elements
    println("Set1: " + set1)
    println("Set2: " + set2)  
 
    // Find the difference between the two sets
    val differenceSet = set1.diff(set2)

    // Print the difference set
    println("Difference Set: " + differenceSet)
  }
}

Sample Output:

Set1: Set(1, 2, 3, 4)
Set2: Set(3, 4, 5, 6)
Difference Set: Set(1, 2)

Explanation:

In the above exercise,

  • First, we create two sets: set1 and set2 where set1 contains the elements 1, 2, 3, and 4, while set2 contains the elements 3, 4, 5, and 6.
  • To find the difference between the two sets, we use the diff method provided by the Set class. The diff method takes another set as an argument and returns a new set that contains elements present in the first set but not in the second set.
  • We store the difference operation result in the differenceSet variable.
  • Finally, we print the difference between two sets using the println function.

Scala Code Editor :

Previous: Creating sets and finding the intersection of two sets.
Next: Check if a set is empty or not.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.