w3resource

Scala Program: Find the maximum element in a set

Scala Set Exercise-13 with Solution

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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/scala-exercises/sets/scala-set-exercise-13.php