Scala Set: Creating an empty set and adding elements
Write a Scala program to create an empty set and add elements to it.
Sample Solution:
Scala Code:
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics