w3resource

Scala Set: Creating sets and finding the union of two sets

Scala Set Exercise-2 with Solution

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

Sample Solution:

Scala Code:

object SetUnionExample {
  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 union of the two sets
    val unionSet = set1.union(set2)

    // Print the union set
    println("Union Set: " + unionSet)
  }
}

Sample Output:

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

Explanation:

In the above exercise,

  • 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 union of the two sets, we use the "union" method provided by the Set class. The union method takes another set as an argument and returns a new set that contains all the distinct elements from both sets.
  • Finally, we print the elements of the union set using string concatenation and the println function.

Scala Code Editor :

Previous: Creating an empty set and adding elements.
Next: Creating sets and finding the intersection of 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://www.w3resource.com/scala-exercises/sets/scala-set-exercise-2.php