Scala Program: Find the maximum element in a set
Write a Scala program to create a set and find the maximum element in the set.
Sample Solution:
Scala Code:
object MaxElementSetExample {
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 maximum element in the set
val maxElement = nums.max
// Print the maximum element
println("Maximum element: " + maxElement)
}
}
Sample Output:
Set: HashSet(10, 20, 50, 40, 30) Maximum element: 50
Explanation:
In the above exercise,
- We create a set "nums" 10, 20, 30, 40, and 50.
- To find the maximum element in the set, we use the max method, which returns the maximum element in the set.
- In the program, we find the maximum element in the set by using the line val maxElement = set.max.
- Finally, we print the set and the maximum element.
Scala Code Editor :
Previous: Checking if a set is disjoint from another set.
Next: Find the minimum element in a set.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics