w3resource

Scala Program: Find the minimum element in a set

Scala Set Exercise-14 with Solution

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?



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