w3resource

Scala set: Check if a set is empty or not

Scala Set Exercise-5 with Solution

Write a Scala program to check if a set is empty or not.

Sample Solution:

Scala Code:

object SetEmptyCheckExample {
  def main(args: Array[String]): Unit = {
    // Create a set
    // val nums = Set(1, 2, 3, 4)
       val nums = Set()
    //Check if the set is empty
    val isEmpty = nums.isEmpty

    // Print the result
    if (isEmpty) {
      println("Set is empty.")
    } else {
      println("Set is not empty.")
    }
  }
}

Sample Output:

Set is not empty.
Set is empty.

Explanation:

In the above exercise,

  • First we create a set "nums" containing elements 1, 2, 3, and 4.
  • To check if the set is empty, we use the isEmpty method provided by the Set class. The isEmpty method returns true if the set does not contain any elements, and false otherwise.
  • We store the result of the "isEmpty" method in the isEmpty variable.
  • Finally, we use an if-else statement to print whether the set is empty or not.

Scala Code Editor :

Previous: Creating sets and finding the difference between two sets
Next: Check if a given element exists 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://w3resource.com/scala-exercises/sets/scala-set-exercise-5.php