Scala Program: Remove an element from a set
Scala Set Exercise-7 with Solution
Write a Scala program to remove an element from a set.
Sample Solution:
Scala Code:
object SetElementRemovalExample {
def main(args: Array[String]): Unit = {
// Create a set
val nums = Set(1, 2, 3, 4)
// Print the initial set
println("Initial Set: " + nums)
// Remove an element from the set
val element = 3
val updatedSet = nums - element
// Print the updated set
println("Updated Set: " + updatedSet)
}
}
Sample Output:
Initial Set: Set(1, 2, 3, 4) Updated Set: Set(1, 2, 4)
Explanation:
In the above exercise,
- First, we create an immutable set "nums" containing 1, 2, 3, and 4.
- To remove an element from the set, we use the - operator. We specify the element to remove from the set.
- In the program, we remove element 3 from the set by using the line val updatedSet = nums - element. This creates a new set updatedSet that does not include element 3.
- Finally, we print the initial set before removal and the updated set after removal.
Scala Code Editor :
Previous: Check if a given element exists in a set.
Next: Find the size of a set.
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-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics