Scala Program: Find the minimum element in a set
Write a Scala program to create a set and find the minimum element in the set.
Sample Solution:
Scala Code:
object MinElementSetExample {
def main(args: Array[String]): Unit = {
// Create a set
val nums = Set(10, 20, 30, 40, 50)
// Print the set
println("Set: " + nums)
// Find the minimum element in the set
val minElement = nums.min
// Print the minimum element
println("Minimum element: " + minElement)
}
}
Sample Output:
Set: HashSet(10, 20, 50, 40, 30) Minimum element: 10
Explanation:
In the above exercise,
- First, we create a set "nums" with the elements 10, 20, 30, 40, and 50.
- To find the minimum element in the set, we use the "min()" method, which returns the minimum element in the set.
- In the program, we find the minimum element in the set by using the line val minElement = set.min.
- Finally, we print the set and the minimum element.
Scala Code Editor :
Previous: Find the maximum element in a set.
Next: Calculating the sum of elements in a set.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics