w3resource

Scala Program: Checking superset relationships between sets

Scala Set Exercise-11 with Solution

Write a Scala program to create a set and check if it is a superset of another set.

Sample Solution:

Scala Code:

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

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

    // Check if set1 is a superset of set2
    val isSuperset = set1.forall(set2.contains)

    // Print the result
    if (isSuperset) {
      println("Set1 is a superset of Set2.")
    } else {
      println("Set1 is not a superset of Set2.")
    }
  }
}

Sample Output:

Set1: Set(1, 2, 3, 4)
Set2: Set(2, 4, 5)
Set1 is not a superset of Set2.

Explanation:

In the above exercise,

  • First, we create two sets set1 and set2 where set1 contains the elements 1, 2, 3, and 4, and set2 contains the elements 2, 4, and 5.
  • To check if set1 is a superset of set2, we use the forall method along with the contains method of set2.
  • In the program, we check if set1 is a superset of set2 by using the line val isSuperset = set1.forall(set2.contains).
  • Finally, we print the sets and the result of the superset check.

Scala Code Editor :

Previous: Checking if a set is a subset of another set.
Next: Checking if a set is disjoint from another 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-11.php