Scala Program: Find the size of a set
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics