w3resource

Scala Program: Find the size of a set

Scala Set Exercise-8 with Solution

Write a Scala program to find the size of a set.

Sample Solution:

Scala Code:

object SetSizeExample {
  def main(args: Array[String]): Unit = {
    // Create a set
    val nums = Set(1, 2, 3, 4)

    // Print the set
    println("Set: " + nums)

    // Find the size of the set
    val size = nums.size

    // Print the size of the set
    println("Size of the Set: " + size)
  }
}

Sample Output:

Set: Set(1, 2, 3, 4)
Size of the Set: 4

Explanation:

In the above exercise,

  • In this program, we create a set "nums" containing the elements 1, 2, 3, and 4.
  • To find the set size, we use the size method.
  • In the program, we find the set size using the line val size = set.size.
  • Finally, we print the set and the size of the set.

Scala Code Editor :

Previous: Remove an element from a set.
Next: Convert a set to a list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.