w3resource

Scala set: Creating sets and finding the intersection of two sets

Scala Set Exercise-3 with Solution

Write a Scala program to create a set and find the intersection of two sets.

Sample Solution:

Scala Code:

object SetIntersectionExample {
  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 intersection of the two sets
    val intersectionSet = set1.intersect(set2)

    // Print the intersection set
    println("Intersection Set: " + intersectionSet)
  }
}

Sample Output:

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

Explanation:

In the above exercise,

  • First, we create two sets: set1 and set2. set1 contains the elements 1, 2, 3, and 4, while set2 contains the elements 3, 4, 5, and 6.
  • To find the intersection of the two sets, we use the intersect method provided by the Set class. The intersect method takes another set as an argument and returns a new set that contains only the common elements between the two sets.
  • We store the result of the intersection operation in the intersectionSet variable.
  • Finally, we print the elements of the intersection set using string concatenation and the println function.

Scala Code Editor :

Previous: Creating sets and finding the union of two sets.
Next: Creating sets and finding the difference between two sets.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/sets/scala-set-exercise-3.php