How to find min and max element from Set in Scala

 189 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about How to find min and max element from Set in Scala.

Scala Set basics

Scala set is a collection that stores only unique values. It doesn’t allow duplicates. Set is Iterable and inherits all functionality of the iterable interface. Check out this detailed post on Scala Set for various Set operations.

Basically Set in Scala has two variants.

  • Immutable Set(Which is the default)
  • Mutable Set(we need to explicitly import mutable Set)

Immutable Set allows us to apply a function on Set but resulting in the creation of a new Set every time. It doesn’t allow us to change the source. On the other hand, the mutable Set allows modifying the source itself.

Let us now learn how to find min and max element from Set in Scala. Scala has provided inbuilt min() and max() operation on collections that help us to identify and min and max values in the collection.

Find the min element in Set

Here, a set has been created and applied min() operation on Set to find the minimum element in Set.

object SetTest {

  def main(args: Array[String]): Unit = {
    var set: Set[Int] = Set(12, 2, 3, 4, 5, 6, 7, 8, 9)

    print(set.min)
  }
}

Output

2

Find the max element in Set

Here, a set has been created and applied max() operation on Set to find the maximum element in Set.

object SetTest {

  def main(args: Array[String]): Unit = {
    var set: Set[Int] = Set(12, 2, 3, 4, 5, 6, 7, 8, 9)

    print(set.max)
  }
}

Output

12

References: Scala Set official documentation

I hope you like this tutorial. Thanks for reading and please give us a thumb up and comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.