w3resource

Scala Program: Find common elements between two sets

Scala Set Exercise-18 with Solution

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

Sample Solution:

Scala Code:

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

    // Print the sets
    println("Set1: " + set1)
    println("Set2: " + set2)

    // Find the common elements between the two sets
    val commonElements = set1.intersect(set2)

    // Print the common elements
    println("Common elements: " + commonElements)
  }
}

Sample Output:

Set1: HashSet(5, 1, 2, 3, 4)
Set2: HashSet(5, 6, 7, 8, 4)
Common elements: HashSet(5, 4)

Explanation:

In the above exercise,

  • First, we create two sets set1 and set2 with some elements.
  • To find the common elements between the two sets, we use the intersect method. This returns a new set containing the elements common to both sets.
  • In the program, we find the common elements between set1 and set2 by using the line val commonElements = set1.intersect(set2).
  • Finally, we print the sets and the common elements.

Scala Code Editor :

Previous: Find the second largest element in a set.

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://www.w3resource.com/scala-exercises/sets/scala-set-exercise-18.php