w3resource

Scala Tuple: Check if a specific element exists in a tuple

Scala Tuple Exercise-7 with Solution

Write a Scala program that checks if a tuple contains a specific element.

Sample Solution:

Scala Code:

object CheckTupleContainsElementExample {
  def main(args: Array[String]): Unit = {
    
    // Create a tuple
    val nums = (1, 2, 3, 4, 5)
    println("Tuple elements: "+nums)
    
    // Check if the tuple contains a specific element
    val elementToCheck = 3
    val containsElement = nums.productIterator.contains(elementToCheck)

    // Print the result
    println(s"Does the tuple contain $elementToCheck? $containsElement")
  }
}

Sample Output:

Tuple elements: (1,2,3,4,5)
Does the tuple contain 3? true

Explanation:

In the above exercise -

  • First, we create a tuple "nums" with elements 1, 2, 3, 4, and 5.
  • To check if the tuple contains a specific element, we use the contains method on tuple.productIterator. The productIterator method returns an iterator over the tuple elements, and we check if it contains the elementToCheck.
  • We assign the resulting boolean value to the variable containsElement.
  • Finally, we print the result using println, including the specific element we are checking.

Scala Code Editor :

Previous: Concatenate two tuples.
Next: Merge two tuples into a single tuple.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.