w3resource

Scala set: Check if a given element exists in a set

Scala Set Exercise-6 with Solution

Write a Scala program to check if a given element exists in a set.

Sample Solution:

Scala Code:

object SetElementCheckExample {
  def main(args: Array[String]): Unit = {
    // Create a set
    val nums = Set(1, 2, 3, 4)
    // Print the set elements
    println("Set: " + nums)

    // Check if an element exists in the set
    val element = 3
    val exists = nums.contains(element)

    // Print the result
    if (exists) {
      println(s"$element exists in the set.")
    } else {
      println(s"$element does not exist in the set.")
    }
  }
}

Sample Output:

Set: Set(1, 2, 3, 4)
3 exists in the set

Explanation:

In the above exercise,

  • First, we create a set 'nums' containing the elements 1, 2, 3, and 4.
  • To check if a given element exists in the set, we use the “contains()” method provided by the Set class. The "contains()" method takes an element as an argument and returns true if the set contains the element, and false otherwise.
  • We store the result of the "contains()" method in the 'exists' variable.
  • Finally, we use an if-else statement to print whether the given element exists in the set or not.

Scala Code Editor :

Previous: Check if a set is empty or not.
Next: Remove an element from 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-6.php