w3resource

Scala Tuple: Find distinct elements in a tuple

Scala Tuple Exercise-9 with Solution

Write a Scala program to find distinct elements in a tuple.

Sample Solution:

Scala Code:

object DistinctElementsInTupleExample {
  def main(args: Array[String]): Unit = {
    // Create a tuple with duplicate elements
    val nums = (1, 2, 3, 2, 4, 3, 5)
    println("Original Tuple elements: "+nums)
    // Find distinct elements in the tuple
    val distinctElements = nums.productIterator.toSet
    // Print the distinct elements
    println("Distinct elements: " + distinctElements)
  }
}

Sample Output:

Original Tuple elements: (1,2,3,2,4,3,5)
Distinct elements: HashSet(5, 1, 2, 3, 4)

Explanation:

In the above exercise -

  • In this program, we create a tuple "nums" with elements (1, 2, 3, 2, 4, 3, 5), which contains duplicate elements.
  • To find distinct elements in the tuple, we convert the tuple to an iterator using productIterator, and then convert the iterator to a set using toSet. Scala automatically removes duplicate elements, giving us only distinct elements.
  • We assign the resulting set of distinct elements to the variable distinctElements.
  • Finally, we print the distinct elements using println.

Scala Code Editor :

Previous: Merge two tuples into a single tuple.
Next: Check if a map is empty.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.