Scala Set: Creating an empty set and adding elements
Scala Set Exercise-1 with Solution
Write a Scala program to create an empty set and add elements to it.
Sample Solution:
Scala Code:
object EmptySetExample {
def main(args: Array[String]): Unit = {
// Create an empty set
var nums_set = Set.empty[Int]
// Add elements to the set
nums_set += 10
nums_set += 20
nums_set += 30
nums_set += 40
nums_set += 50
// Print the set
println("Set elements: " + nums_set)
}
}
Sample Output:
Set elements: HashSet(10, 20, 50, 40, 30)
Explanation:
In the above exercise,
- First, we create an empty set nums_setusing the Set.empty[Int] syntax. The Int specifies the type of elements that the set will contain.
- We then add elements to the set using the += operator. In this example, we add the integers 10, 20, 30, 40 and 50 to the set.
- Finally, we print the elements of the set using string concatenation and the println function.
Scala Code Editor :
Previous: Scala Sets Exercises Home.
Next: Creating sets and finding the union of two sets.
What is the difficulty level of this exercise?
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://w3resource.com/scala-exercises/sets/scala-set-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics