w3resource

Scala Program: Find the second largest element in a set

Scala Set Exercise-17 with Solution

Write a Scala program to create a set and find the second largest element in the set.

Sample Solution:

Scala Code:

object SecondLargestElementSetExample {
  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 second largest element in the set
    val secondLargest = nums.toList.sorted.reverse(1)

    // Print the second largest element
    println("Second largest element: " + secondLargest)
  }
}

Sample Output:

Set: HashSet(10, 20, 50, 40, 30)
Second largest element: 40

Explanation:

In the above exercise,

  • First, we create a set "nums" with the elements 10, 20, 30, 40, and 50.
  • To find the second largest element in the set, we convert the set to a list using the toList method, sort the list in descending order using the "sorted" method with the reverse method, and then access the element at index 1, which corresponds to the second largest element.
  • In the program, we find the second largest element in the set by using the line val secondLargest = set.toList.sorted.reverse(1).
  • Finally, we print the set and the second largest element.

Scala Code Editor :

Previous: Calculating the average of elements in a set.
Next: Find common elements between two sets.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.